2017-06-19 1 views
0

Wie kann ich den folgenden Code mit Observables in rxjs implementieren?Wie implementiert man folgende mit rxjs Observables?

Was ich hier erreichen möchte, ist, dass ich eine Reihe von Funktionen habe, von denen jede ein Objekt akzeptiert, es modifiziert und das Objekt zur nächsten Funktion im Stapel zurückbringt.

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

Wie kann ich das gleiche mit Observablen in Rxjs implementieren?

+1

Ich verstehe wirklich nicht, warum Sie das mit beobachtbaren tun würden – Maxime

Antwort

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" */ 
Verwandte Themen