简体   繁体   中英

RxJS - Observable does not execute when takeUntil and its notifier observable emits in the same internal observable

Code:

    const main$ = of(true);
    const int$ = interval(2000);
    const notifier$ = new Subject();

    main$.pipe(
      switchMap(() => int$.pipe(
        tap(() => {
          // some logic for when to trigger notifier
          notifier$.next(1); // after some intervals
        }),
        takeUntil(notifier$),
      )),
      tap(() => {// never reach here})
    ).subscribe(() => {
      // never reach here
    });

In the above code, takeUntil stops the interval when the notifier$ emits but it does not call subscribe() ever and never reach the operators eg. tap() (see code) after takeUntil . Why is that? Am I missing something?

the takeUntil operator emits the values emitted by a source Observable that would be your main$ Observable until a notifier Observable emits a value as it is being done by the notifier$ Subject. Thus, after notifier$ emits a value on the next call within the very first iteration of your interval, the takeUntil prevents the underlying Observable to be propagated any further, meaning that the tap operator will never be reached.

If you were using a different implementation for your notifier$ such as timer , you could observe the tap operator to be called until the timer elapses and thereby triggering the takeUntil .

    const main$ = of(true);
    const int$ = interval(2000);
    const notifier$ = timer(10000);

    main$.pipe(
      switchMap(() => int$.pipe(
        tap(() => {
          // some logic for when to trigger notifier
        }),
        takeUntil(notifier$),
      )),
      tap((result) => {
        console.log(result)
      })
    ).subscribe((result) => {
      // will be reached four times.
    });
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM