![](/img/trans.png)
[英]How to replace flatMap and mergeMap in rxjs 6.4.0 Angular
[英]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)
是相互獨立的。 相反,您可以使用諸如forkJoin
、 combineLatest
或zip
類的函數來並行獲取來自它們的通知。
嘗試以下
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 的發射流打開,您可以使用combineLatest
或zip
代替。 在這種情況下,您可以將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.