简体   繁体   English

我应该在Angular中使用switchMap,flatMap还是任何其他rxjs运算符

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

I have two streams of data, second one depends on first one, but i want to be able to catch a change of second one. 我有两个数据流,第二个数据流取决于第一个数据流,但是我希望能够捕获第二个数据流的变化。 I wrote 2 functions for creating observables. 我写了两个创建可观察对象的函数。 I am wondering if this implementation is correct. 我想知道这种实现是否正确。

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

If you could be more specific about what you are asking it would help but from what I understand it looks fine. 如果您可以更具体地询问自己的问题,这会有所帮助,但据我了解,这看起来不错。

I think that you probably want to use switchMap instead of flatMap. 我认为您可能想使用switchMap而不是flatMap。 FlatMap will maintain multiple inner subscriptions while SwitchMap will only maintain a subscription to the latest inner observable. FlatMap将维护多个内部订阅,而SwitchMap将仅维护对最新内部可观察者的订阅。 So if you want to only get values from the inner observable based on the output of the source then switchMap will do that. 因此,如果您只想根据源的输出从内部可观察的值中获取值,则switchMap将执行此操作。

Not sure of your use cases but you might want to consider applying a filter instead of returning Observable.empty(). 不确定用例,但您可能要考虑应用过滤器,而不是返回Observable.empty()。

Here is an example: 这是一个例子:

 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