簡體   English   中英

我應該在Angular中使用switchMap,flatMap還是任何其他rxjs運算符

[英]Should i use switchMap, flatMap or any other rxjs operator in Angular

我有兩個數據流,第二個數據流取決於第一個數據流,但是我希望能夠捕獲第二個數據流的變化。 我寫了兩個創建可觀察對象的函數。 我想知道這種實現是否正確。

firstObservable(){
  ...
};
secondObservable(someValue){
  ...
}
let subscription = firstObservable().switchMap(r => {
  if (r.someValue){
    return secondObservable(r.someValue);
  }else{
    return Observable.empty();
  }
}).subscribe( ... );

如果您可以更具體地詢問自己的問題,這會有所幫助,但據我了解,這看起來不錯。

我認為您可能想使用switchMap而不是flatMap。 FlatMap將維護多個內部訂閱,而SwitchMap將僅維護對最新內部可觀察者的訂閱。 因此,如果您只想根據源的輸出從內部可觀察的值中獲取值,則switchMap將執行此操作。

不確定用例,但您可能要考慮應用過濾器,而不是返回Observable.empty()。

這是一個例子:

 const firstObservable = Rx.Observable.create((o) => { o.next(); setTimeout(() => o.next(1), 1000); setTimeout(() => o.next(), 2000); setTimeout(() => o.next(2), 3000); setTimeout(() => o.complete(), 4000); }).do(console.log.bind(null, 'first: next'), console.log.bind(null, 'first: error'), console.log.bind(null, 'first: complete')); const secondObservable = (x) => Rx.Observable.interval(x * 500).take(5) .do(console.log.bind(null, 'second: next'), console.log.bind(null, 'second: error'), console.log.bind(null, 'second: complete')); firstObservable.filter(x => x).switchMap(x => secondObservable(x)) .subscribe(console.log.bind(null, 'stream: next'), console.log.bind(null, 'stream: error'), console.log.bind(null, 'stream: complete')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script> 

暫無
暫無

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

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