2017-02-16 287 views
0

我有兩個流,看起來如下:繼續流之後訂閱

const source1 = Rx.Observable.of([1,2,3,4,5]) 
    .map(() => "I am source 1") 
    .do((x) => console.log(x)); 
const sub1 = source1.subscribe((v) => console.log("Subscribe 2")); 

const source2 = Rx.Observable.fromEvent(document, 'click') 
    .do(() => console.log("execute!")) 
    .switchMapTo(source1) 
    .do(() => console.log("After switch map.")) 
    .map((x) => "source2"); 

source2.subscribe((x) => console.log(x)); 

沒有點擊文件我有以下的輸出:

"I am source 1" 
"Subscribe 2" 

而且點擊的輸出是:

"execute!" 
"I am source 1" 
"After switch map." 
"source2" 

如何強制流source1通過進一步點擊和繼續流source2

我經過以下幾個輸出點擊期望:

"I am source 1" 
"Subscribe 2" 
"execute!" 
"I am source 1" 
"After switch map." 
"source2" 

回答

1

觀測量可以被認爲是功能。訂閱就像調用函數一樣。

const o = Rx.Observable.of(1); 
o.subscribe(x => console.log(x)); 

是非常相似的

const f =() => 1; 
console.log (f()); 

就像調用一個函數不修改功能。訂閱Observable不會修改觀察值。訂閱不是附加任何方式的Observable。它是持有任何狀態的退回訂閱。


兩個呼叫在你的榜樣訂閱是完全獨立的,是與此相同:

const source1 = Rx.Observable.of([1,2,3,4,5]) 
    .map(() => "I am source 1") 
    .do((x) => console.log(x)); 
const sub1 = source1.subscribe((v) => console.log("Subscribe 2")); 

const source1_v2 = Rx.Observable.of([1,2,3,4,5]) 
    .map(() => "I am the same as source 1") 
    .do((x) => console.log(x)); 

const source2 = Rx.Observable.fromEvent(document, 'click') 
    .do(() => console.log("execute!")) 
    .switchMapTo(source1_v2) 
    .do(() => console.log("After switch map.")) 
    .map((x) => "source2"); 

source2.subscribe((x) => console.log(x));