typescript - RxJS:沿可观察链传递数据的干净方式?
问题描述
我似乎经常遇到这种情况,我需要沿着一系列流传递数据。换句话说,我有依赖于一个或多个其他可观察对象的输出的可观察对象。
下面是通过一个简单示例实现此目的的 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))
);
推荐阅读
- azure - 如何根据文件模式将不同的文件加载到不同的表中?
- javascript - 在 onSelect 处从 material-ui 自动完成中检索条目的键,而不是值
- react-native - es6 和 redux 嵌套对象的可变性
- flutter - 用可为空的值颤振 FutureBuilder
- cloud-foundry - Pivotal Cloud Foundry 中的物理文件位置
- javascript - threejs lerp 和相机动画不流畅
- javascript - JavaScript - 为什么 innerHTML 属性在包含 HTML 时显示为文本?
- javascript - 没有数据的 React Native 中不同的、不同的 FlatList 项
- laravel - 邮件程序错误:SMTP 错误:无法连接到 SMTP 主机
- javascript - 这个出口是什么意思?这是一个执行两个功能的对象吗?