簡體   English   中英

如何使用 MergeMap 或 FlatMap 或使用 rxJs-operators 的一些更好的方法編寫以下代碼?

[英]How to write below code using MergeMap or FlatMap or some better way with rxJs-operators?

我有兩個可觀察的管道。 我需要一個接一個地運行並比較兩個值是否相等。 我嘗試了下面的代碼。這應該可以工作,當第一個可觀察值發出時,它應該去取第二個 obserbla 值,並且應該首先返回值。我需要一些專家幫助,以更好的方式重新編寫此代碼。

   this.selectedUnitDetailModel$.pipe(shareReplayUntil(this.destroySub)).subscribe(
          (res: UnitDetail) =>{
              if(res.unitTwo){
                this.appStore.select(selectUnit).
                pipe(shareReplayUntil(this.destroySub)).subscribe(
                  (unitId: string) => {
                    if(unitId ===  res.unitTwo){
                      this.sameUnit = true;
                    }else{
                      this.sameUnit = false;
                    }
                  });
              }
          }
       );
this.selectedUnitDetailModel$.pipe(shareReplayUntil(this.destroySub),mergeMap(
          (res: UnitDetail) =>{
              if(res.unitTwo){
               return this.appStore.select(selectUnit).
                pipe(shareReplayUntil(this.destroySub),map(
                  (unitId: string) =>  unitId ===  res.unitTwo);
              }
          }
       ).subscribe({
        next: (sameUnit: boolean) => {
           //do something 
        }
       });

您不需要更高階的運算符,因為可觀察對象this.selectedUnitDetailModel$this.appStore.select(selectUnit)是相互獨立的。 相反,您可以使用諸如forkJoincombineLatestzip類的函數來並行獲取來自它們的通知。

你可以在這里找到這些函數的不同之

嘗試以下

forkJoin(
  this.selectedUnitDetailModel$.pipe(take(1)),      // <-- complete on first emission
  this.appStore.select(selectUnit).pipe(take(1))    // <-- complete on first emission
).subscribe(
  ([res, unitId]) => this.sameUnit = res.unitTwo === unitId,
  (error) => console.log(error)                     // <-- handle error
);

forkJoin僅在源 observable 完成時發出,所以我已經take(1)到每個 observable 中。 forkJoin現在將在每個 observable 和 complete 的第一次發射時發射。 所以你的shareReplayUntil(this.destroySub)的需要被減輕了。

但是,如果您需要保持來自 observable 的發射流打開,您可以使用combineLatestzip代替。 在這種情況下,您可以將take(1)替換為您的“shareReplayUntil(this.destroySub)”。

更新: this.selectedUnitDetailModel$ observable 的連續流

就像我之前說的,您可以使用combineLatest而不是forkJoin來啟用連續的數據流。

嘗試以下

import { Subject, combineLatest } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

combineLatest(
  this.selectedUnitDetailModel$,
  this.appStore.select(selectUnit)
).pipe(
  takeUntil(this.destroySub)         // <-- replaced with `takeUntil` operator
).subscribe(
  ([res, unitId]) => this.sameUnit = res.unitTwo === unitId,
  (error) => console.log(error)                     // <-- handle error
);

暫無
暫無

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

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