如何有条件地使用"flatmap"运算符? (角度2/rxjs) [英] How to use the 'flatmap' operator conditionally ? (Angular 2/rxjs)

查看:113
本文介绍了如何有条件地使用"flatmap"运算符? (角度2/rxjs)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是有条件地运行一系列可观察对象.

What I'm trying to achieve is to run a series of observables conditionally.

return observable.map(response => response)
       .flatmap(response1 => observable1(response1))
       .flatmap(response2 => observable2(response2))
       .flatmap(response3 => observable3(response3))

我需要检查response1并在需要时调用其余的可观察对象,否则我需要返回response1并中断执行,依此类推.

I need to check the response1 and invoke the remaining observables if needed, else I need to return response1 and break the execution and so on.

我已经经历了以下SO问题,但它们似乎并没有回答我的问题

I've gone through the following SO questions but they doesn't seem to answer my question

有条件地选择RxJS中的可观察对象

如果可观察为有条件,则为RXJS

处理RxJ的flatMap流中的错误并继续进行处理

我是rxjs的新手,如果问题似乎太la脚,请原谅我.

I'm new to rxjs, so forgive me if the question seems too lame.

任何帮助将不胜感激.

Any help will be appreciated.

谢谢

推荐答案

这就像调用多个连续的HTTP请求(结果相互依赖)一样.在这里,您要使用concatMap(),因为它会等到回调函数返回的Observable完成.

This is like calling multiple consecutive HTTP requests where results depend on each other. This is where you want to use concatMap() instead because it'll wait until the Observable returned from the callback function completes.

很难从描述中分辨出您到底想做什么,但是如果您需要停止传播结果(并避免调用不必要的HTTP请求),请使用takeWhile()运算符或简单的filter()运算符.

It's hard to tell what exactly you want to do from your description but if you need to stop propagating the results (and avoid calling unnecessary HTTP requests) have a look takeWhile() operator or simple filter() operators.

使用filter():

return observable
    .concatMap(response => response)
    .filter(response1 => response1.whatever === true)
    .concatMap(response1 => observable1(response1))
    .filter(response2 => response2.whatever === true)
    .concatMap(response2 => observable2(response2))
    .filter(response3 => response3.whatever === true)

如果未通过filter测试,则不会进一步传播该项目.但是,源observable仍可以发出将通过链传递的值.换句话说,filter运算符不会完成该链.

This simply won't propagate the item further if it fails the filter test. However the source observable can still emit values that'll go through the chain. In other words the filter operator doesn't complete the chain.

使用takeWhile():

return observable
    .concatMap(response => response)
    .takeWhile(response1 => response1.whatever === true)
    .concatMap(response1 => observable1(response1))
    .takeWhile(response2 => response2.whatever === true)
    .concatMap(response2 => observable2(response2))
    .takeWhile(response3 => response3.whatever === true)

如果任何takeWhile()结果为false,它将完成链,并且无法发出其他值.

If any of the takeWhile() result into false it'll complete the chain and no other value can be emitted.

这篇关于如何有条件地使用"flatmap"运算符? (角度2/rxjs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆