【问题标题】:How to implement following using rxjs Observables?如何使用 rxjs Observables 实现以下功能?
【发布时间】:2017-06-19 09:31:48
【问题描述】:

如何在 rxjs 中使用 Observables 实现以下代码?

我在这里想要实现的是我有一个函数数组,每个函数都接受一个对象,修改它并将对象返回给堆栈中的下一个函数。

function A(res:SomeType){
    //Do Something
    return res;
}

function B(res:SomeType){
    //Do Something
    return res;
}

function C(res:SomeType){
    //Do Something
    return res;
}

let fnPipe = [];

fnPipe.push(A); 
fnPipe.push(B);
fnPipe.push(C);

obj= {key:"val"};

fnPipe.forEach((fn)=>{
    obj= fn(obj);
});
console.log(obj);

如何在 rxjs 中使用 observables 实现相同的功能?

【问题讨论】:

  • 我真的不明白你为什么要用 observable 来做这个

标签: javascript rxjs observable rxjs5


【解决方案1】:
let fn$ = Observable.from([
  x => x + "a",
  x => x + "b",
  x => x + "c"
])
let value$ = Observable.of("x", "y", "z")

value$
  .concatMap(val => fn$.scan((acc, fun) => fun(acc), val))
  .subscribe(console.log)

/* prints
"xa"
"xab"
"xabc"
"ya"
"yab"
"yabc"
"za"
"zab"
"zabc" */

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2018-02-14
    • 1970-01-01
    • 2017-06-22
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多