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