rxjs仅在第一次执行tap [英] rxjs execute tap only at the first time
本文介绍了rxjs仅在第一次执行tap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在获得第一个发射值时才执行tap()
I want to execute tap() only when i get the first emitted value
类似的东西:
Observable
.pipe(
tap(() => { /* execute only when I get the first emitted value */ })
)
.subscribe(() => {
// .....
})
推荐答案
您可以在地图操作符(如 concatMap
)中使用索引.与其他方法不同,这对于所选索引是完全灵活的.假设您要点击第二个发射 index === 1
或任何谓词,例如 index%2 === 0
You can use the index in map operators like concatMap
. Unlike other approaches this is totally flexible about the chosen index. Let's say if you want tap on 2nd emission index === 1
or any predicate like index % 2 === 0
// these are because of using rxjs from CDN in code snippet, ignore them
const {of, interval} = rxjs;
const {take, tap, concatMap} = rxjs.operators;
// main code
const stream = interval(250).pipe(take(4))
stream.pipe(
concatMap((value, index) => index === 0
? of(value).pipe(
tap(() => console.log('tap'))
)
: of(value)
)
)
.subscribe(x => console.log(x));
<script src="https://unpkg.com/@reactivex/rxjs@6.x/dist/global/rxjs.umd.js"></script>
这篇关于rxjs仅在第一次执行tap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文