为什么价值仍然排放

时间:2016-12-20 08:38:11

标签: javascript typescript rxjs5

我有以下可连接的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仍会发出一个项目,即使我取消订阅它?

1 个答案:

答案 0 :(得分:1)

.connect()基本上也是订阅,所以为了停止流,你必须"断开" 它,像这样:

let connection;
setTimeout(() => {
 connection = example.connect(); 
},5000)

setTimeout(() => {
 connection.unsubscribe();
 subscribe.unsubscribe(); 
},7000)