繁体   English   中英

RxJS - 当 takeUntil 及其通知器 observable 在同一个内部 observable 中发出时,Observable 不会执行

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

代码:

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

在上面的代码中,当notifier$发出时takeUntil停止interval ,但它不会调用subscribe()并且永远不会到达运算符,例如。 takeUntil之后的tap() (参见代码)。 这是为什么? 我错过了什么吗?

takeUntil操作符发出源 Observable 发出的值,这将是您的main$ Observable,直到通知器 Observable 发出一个值,因为它是由notifier$主题完成的。 因此,在notifier$在间隔的第一次迭代内的next调用中发出一个值之后, takeUntil阻止底层的 Observable 进一步传播,这意味着永远不会到达tap运算符。

如果您对notifier$使用不同的实现,例如timer ,您可以观察到要调用的tap操作符,直到计时器结束并因此触发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.
    });
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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