我需要一种方法来将值从一个observable传递给两个函数,每个函数接受一个值,然后每个函数返回一个observable(只发出一个值,然后完成)。我希望.combineLatest()
允许我传递投影功能,但事实并非如此。
示例代码(不工作):
const ac = [1, 2, 3]; // only as example, I have complex types in my array not numbers
Observable.from(ac)
.combineLatest(
// processFn should get a number as argument and return Observable<number>
// does not work because .combineLatest does not accept two functions as arguments :(
n => processFn1(n),
n => processFn2(n)
)
.map(([result1, result2] => {
// result1, result2 should be flat numbers here, not Observables
})
);
关于如何做到这一点的任何想法?
答案 0 :(得分:1)
您使用combineLatest运算符的想法是正确的,但它位于错误的位置。如果你需要展平observable,你应该使用mergeMap。这是一个符合您期望的JSBIN:http://jsbin.com/rutovot/4/edit?html,js,console
代码如下所示:
const ac = [1, 2, 3];
Rx.Observable.from(ac)
// use mergeMap, it takes a function that accepts a value and
// returns an observable. MergeMap will listen to this observable
// under the hood and next the result of this observable down the
// the chain
.mergeMap(val => {
// Here we return an observable that combines the result of the
// call to both the functions
return Rx.Observable.combineLatest(fake(val), fake2(val));
})
.subscribe(val => console.log(val));