rxjs execute tap only at the first time

前端 未结 6 1105
臣服心动
臣服心动 2020-12-19 02:18

I want to execute tap() only when i get the first emitted value

Something like:

Observable
  .pipe(
     tap(() => { /* execute only when I get th         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 02:50

    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));

提交回复
热议问题