【问题标题】:RxJS5: .combineLatest() with projection function?RxJS5:.combineLatest() 与投影功能?
【发布时间】:2017-03-31 19:33:22
【问题描述】:

我需要一种方法将值从一个 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
    })
);

你知道怎么做吗?

【问题讨论】:

    标签: javascript typescript rxjs rxjs5 reactivex


    【解决方案1】:

    您使用 combineLatest 运算符的想法是正确的,但它在错误的位置。如果你需要扁平化 observables,你应该使用 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));
    

    【讨论】:

    • 经常使用 RxJS 但需要一些时间来适应它:)
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多