Rxjs嵌套订阅具有多个内部订阅 [英] Rxjs nested subscribe with multiple inner subscriptions

查看:75
本文介绍了Rxjs嵌套订阅具有多个内部订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重写的基于原始承诺的代码:

Original promise based code I'm trying to rewrite:

parentPromise
    .then((parentResult) => {
        childPromise1
            .then(child1Result => child1Handler(parentResult, child1Result));
        childPromise2
            .then(child1Result => child2Handler(parentResult, child2Result));
        childPromise3
            .then(child1Result => child3Handler(parentResult, child3Result));
    });   

我正在尝试找到一种方法来避免

I'm trying to figure a way how to avoid the nested subscriptions anti-pattern in the following scenario:

parent$
    .pipe(takeUntil(onDestroy$))
    .subscribe((parentResult) => {
        child1$
            .pipe(takeUntil(onDestroy$))
            .subscribe(child1Result => child1Handler(parentResult, child1Result));
        child2$
            .pipe(takeUntil(onDestroy$))
            .subscribe(child2Result => child2Handler(parentResult, child2Result));
        child3$
            .pipe(takeUntil(onDestroy$))
            .subscribe(child3Result => child3Handler(parentResult, child3Result));
    });

执行此操作的正确"RxJS方法"是什么?

What would be the correct 'RxJS way' to do this?

推荐答案

这对我来说似乎很奇怪.每当 parentResult 到达时,您都在为每个孩子创建新的订阅.即使这些最终确实会被销毁(假设 onDestroy $ 实现是正确的),也似乎是错误的.

That seems pretty strange to me. You're creating new subscription for each child every time parentResult arrives. Even though those eventually indeed will be destroyed (assuming onDestroy$ implementation is correct), seems wrong.

您可能希望每个孩子都有 withLatestFrom(parent $)和三个独立的管道.

You probably want withLatestFrom(parent$) and three separate pipes for each child.

它可能看起来像: child1 $ .pipe(takeUntil(globalDeath $),withLatestFrom(parent $)).subscribe(([[childResult,parentResult])=> ...).不确定我的JS是否正确,目前无​​法对其进行测试;但要点是:每次 child1 $ 触发时,您都会从 parent $ 获得最新结果.请注意,如有必要,您可以反转方向( withLatestFrom(child1 $)).

It might look something like: child1$.pipe(takeUntil(globalDeath$), withLatestFrom(parent$)).subscribe(([childResult, parentResult]) => ...). Not sure if my JS is correct, can't test it at the moment; but the point is: you're getting the latest result from the parent$ every time child1$ fires. Note that you can reverse the direction if necessary (withLatestFrom(child1$)).

这篇关于Rxjs嵌套订阅具有多个内部订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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