javascript - RxJS5: .combineLatest() 有投影功能?

标签 javascript typescript rxjs rxjs5 reactivex

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

知道怎么做吗?

最佳答案

您使用 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));

关于javascript - RxJS5: .combineLatest() 有投影功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40651842/

相关文章:

javascript - AngularJs 发送 OPTION 而不是 POST 请求

javascript - 这些绑定(bind)方法在 Angular 上有什么区别?

typescript - 如何断言一个受歧视的联合是 typescript 单元测试中的某个变体?

javascript - VSCode 是否支持 react 中的 CSS 变量?错误

promise - 获得可观察性,但在激活之前等待 promise

angular - 捕获错误并返回 of(undefined) 会停止流(Angular 7,rxjs6)

javascript - 如何将 Controller 的范围属性传递给自定义指令?

Javascript - 在类中转换对象

JavaScript 动态变量名称

javascript - 将 Observable<String[]> 转换为 Observable<DataType[]>