0

How can I implement the following code using Observables in rxjs?

What I am trying to achieve here is that I have an array of functions, each of which accepts an object, modifies it and returns the object to the next function in the stack.

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);

How can I implement the same using observables in rxjs?

1
  • 1
    I really don't understand why you'd do that with observable Commented Jun 19, 2017 at 11:19

1 Answer 1

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" */
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.