簡體   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