我有以下可连接的observable:
//emit value every 1 second
const source = Rx.Observable.interval(1000);
const example = source
//side effects will be executed once
.do(() => console.log('Do Something!'))
//do nothing until connect() is called
.publish();
/*
source will not emit values until connect() is called
output: (after 5s)
"Do Something!"
"Subscriber One: 0"
"Subscriber Two: 0"
"Do Something!"
"Subscriber One: 1"
"Subscriber Two: 1"
*/
const subscribe = example.subscribe(val => console.log(`Subscriber One: ${val}`));
//call connect after 5 seconds, causing source to begin emitting items
setTimeout(() => {
example.connect();
},5000)
setTimeout(() => {
subscribe.unsubscribe();
},7000)
为什么源observable仍会发出一个项目,即使我取消订阅它?
答案 0 :(得分:1)
.connect()
基本上也是订阅,所以为了停止流,你必须"断开" 它,像这样:
let connection;
setTimeout(() => {
connection = example.connect();
},5000)
setTimeout(() => {
connection.unsubscribe();
subscribe.unsubscribe();
},7000)