RxJS - 收集异步操作结果
RxJS - Collect async operation results
我想对数组的每个元素执行异步操作并将其结果收集到字典中。我目前的做法是:
let asyncOp = () => Rx.Observable.interval(300).take(1);
let dict = {};
Rx.Observable.from(['a', 'b'])
.mergeMap(el => asyncOp()
.map(asyncOpRes => dict[el] = asyncOpRes)
.do(state => console.log('dict state: ', dict))
)
.takeLast(2)
.take(1)
.map(() => dict)
.subscribe(res => console.log('dict result: ', res));
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
基本上这就像我想要的那样工作,但它似乎是 RxJs 运算符的尴尬用法。所以我需要以下方面的帮助:
- 避免 dict 突变(尝试使用 scan(),但不知道如何在这里使用它。有一个 mergeScan() 方法,但这里相同)
- takeLast 和 take - 的用法应该可以简化吗?
我想我缺少一个 RxJS 运算符来帮助我简化它。
到"execute an async operation on every element of an array and collect its results in a dictionary"可以使用mergeMap
and reduce
函数显着简化代码:
import * as Rx from "rxjs/Rx";
const asyncOp = () => Rx.Observable.interval(300).take(1);
Rx.Observable.from(["a", "b"])
// Perform the async operation on the values emitted from the
// observable and map the emitted value and async result into
// an object.
.mergeMap((key) => asyncOp().map((result) => ({ key, result })))
// Use reduce to build an object containing the emitted values
// (the keys) and the async results.
.reduce((acc, value) => { acc[value.key] = value.result; return acc; }, {})
.subscribe((value) => { console.log(value); });
我想对数组的每个元素执行异步操作并将其结果收集到字典中。我目前的做法是:
let asyncOp = () => Rx.Observable.interval(300).take(1);
let dict = {};
Rx.Observable.from(['a', 'b'])
.mergeMap(el => asyncOp()
.map(asyncOpRes => dict[el] = asyncOpRes)
.do(state => console.log('dict state: ', dict))
)
.takeLast(2)
.take(1)
.map(() => dict)
.subscribe(res => console.log('dict result: ', res));
<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
基本上这就像我想要的那样工作,但它似乎是 RxJs 运算符的尴尬用法。所以我需要以下方面的帮助:
- 避免 dict 突变(尝试使用 scan(),但不知道如何在这里使用它。有一个 mergeScan() 方法,但这里相同)
- takeLast 和 take - 的用法应该可以简化吗?
我想我缺少一个 RxJS 运算符来帮助我简化它。
到"execute an async operation on every element of an array and collect its results in a dictionary"可以使用mergeMap
and reduce
函数显着简化代码:
import * as Rx from "rxjs/Rx";
const asyncOp = () => Rx.Observable.interval(300).take(1);
Rx.Observable.from(["a", "b"])
// Perform the async operation on the values emitted from the
// observable and map the emitted value and async result into
// an object.
.mergeMap((key) => asyncOp().map((result) => ({ key, result })))
// Use reduce to build an object containing the emitted values
// (the keys) and the async results.
.reduce((acc, value) => { acc[value.key] = value.result; return acc; }, {})
.subscribe((value) => { console.log(value); });