rxjs execute tap only at the first time

前端 未结 6 1008
臣服心动
臣服心动 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:54

    You can share() your main Observable like below:

    import { timer, of, BehaviorSubject, interval } from 'rxjs';
    import { tap, mapTo, share, shareReplay, } from 'rxjs/operators';
    
    const source$ = timer(1000)
    .pipe(
      tap((v) => console.log('SIDE EFFECT')),
      mapTo('RESULT')
    )
    const sharedSource$ = source$.pipe(share());
    // or shareReplay(1) if you want to ensure every subscriber get the last value event if they will subscribe later;
    
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    sharedSource$.subscribe(console.log);
    

    https://stackblitz.com/edit/typescript-qpnbkm?embed=1&file=index.ts

    This is an example like in learn-rxjs

提交回复
热议问题