我有两个流,看起来如下:
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"
答案 0 :(得分:1)
可以将Observable视为函数。订阅就像调用函数一样。
即
const o = Rx.Observable.of(1);
o.subscribe(x => console.log(x));
与
非常相似const f = () => 1;
console.log ( f() );
就像调用函数一样不会修改函数。订阅Observable不会修改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));