簡體   English   中英

將 RxJS observables 與第一個操作符結合

[英]Combine RxJS observables with first operator

這個問題可能不是最好的,因為我是 rxjs 的新手。 我提前道歉。

 this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((queryParams) => {
      this.one();
      this.two();
    });

    this.route.queryParams.pipe(first(), takeUntil(this.destroy$)).subscribe((queryParams) => {
      this.three();
    });

是否有可能將這兩個 observable 合二為一? this.three需要觸發一次,因為使用了first運算符。

如果您需要發出的值來進行一些控制,您可以使用combineLatest以這種方式組合可觀察對象:

combineLatest([observable1$, observable2$]).subscribe(([val1, val2]) => {})

當您的任何 observable 發出一個值 combineLatest 將發出每個的最后一個值,或者您可以使用merge來獲取單個 observable

您可以使用合並來做到這一點:

const queryParams$ = this.route.queryParams.pipe(share());

const executeOthers$ = queryParams$.pipe(
  tap(() => {
   this.one();
   this.two();
  })
);
const executeThree$ =  queryParams$.pipe(
  first(),
  tap(() => this.three())
);

merge(executeOthers$, executeThree$).pipe(
    takeUntil(this.destroy$)
).subscribe();

通過這樣做,您可以確保在第一個 queryParams 發射時執行了 Three() 方法。 其他兩種方法(一種和兩種)將首先執行,並且每次更改路由參數時都會執行。

最干凈的解決方案可能只訂閱兩次。

如果您確實更喜歡將兩者結合起來,我會這樣做:

this.route.queryParams.pipe(
  takeUntil(this.destroy$),
  map((value, index) => ({value, index})),
).subscribe(({value: queryParams, index}) => {
  if(index === 0){
    this.three();
  }
  this.one();
  this.two();
});

這會在流的末尾添加一個索引,因此您可以知道發出了多少個值並使用它來執行某些邏輯。


另一種解決方案是基本上tap第一個值。 由於tap不給我們一個索引,我們可以使用map並通過原樣傳遞值。

this.route.queryParams.pipe(
  takeUntil(this.destroy$),
  map((value, index) => {
    if(index === 0) this.three();
    return value;
  }),
).subscribe(queryParams => {
  this.one();
  this.two();
});

另一個解決方案是創建一個布爾值來跟蹤您是否在流中的第一個值上。 為此,您基本上需要創建一個自定義運算符。

this.route.queryParams.pipe(
  takeUntil(this.destroy$),
  o => defer(() => {
    let first = true;
    return o.pipe(
      tap(val => {
        if(first){
          this.three();
          first = false;
        }
      })
    )
  }),
).subscribe(queryParams => {
  this.one();
  this.two();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM