gpt4 book ai didi

typescript - RxJS:沿可观察链传递数据的简洁方法?

转载 作者:行者123 更新时间:2023-12-05 06:26:02 24 4
gpt4 key购买 nike

我似乎经常遇到这种情况,我需要沿着流链传递数据。换句话说,我有一些依赖于一个或多个其他可观察对象的输出的可观察对象。

下面是通过一个简单示例实现此目的的 3 种方法,但它们都不像“RxJS”方式。有更好的方法吗?

// Method #1 - looks clean, but feels hacky

let firstResponse = null;
performFirstAction().pipe(
tap(_firstResponse => (firstResponse = _firstResponse)),
switchMap(_firstResponse => performSecondAction(_firstResponse)),
switchMap(secondResponse => performThirdAction(firstResponse, secondResponse))
);

// Method #2 - gets ugly real quick as it scales

performFirstAction().pipe(
switchMap(firstResponse =>
performSecondAction(firstResponse).pipe(
map(secondResponse => ({ firstResponse, secondResponse }))
)
),
switchMap(({ firstResponse, secondResponse }) =>
performThirdAction(firstResponse, secondResponse)
)
);

// Method #3 - might as well just use callbacks at this point

performFirstAction().pipe(
switchMap(firstResponse =>
performSecondAction(firstResponse).pipe(
switchMap(secondResponse =>
performThirdAction(firstResponse, secondResponse)
)
)
)
);

最佳答案

最简洁、最易读的方法是将中间 Observable 存储在它们自己的变量中

const firstResponse$ = performFirstAction();

const secondResponse$ = firstResponse$.pipe(
switchMap(firstResponse => performSecondAction(firstResponse)),
);

const thirdResponse$ = secondResponse$.pipe(
withLatestFrom(firstResponse$),
switchMap(([secondResponse, firstResponse]) => performThirdAction(firstResponse, secondResponse))
);

关于typescript - RxJS:沿可观察链传递数据的简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56468840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com