【问题标题】:Why values still emitted为什么仍然发出值
【发布时间】:2017-05-05 09:50:20
【问题描述】:

我有以下可连接的 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 仍然发出一个项目?

【问题讨论】:

  • observable 不会因为没有订阅者而停止它所做的事情。要么杀死 observable,要么将 console.log 函数放入订阅中。

标签: javascript typescript rxjs5


【解决方案1】:

.connect() 基本上也是一个订阅,所以为了停止流,你必须“断开”它,例如:

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

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

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-07-24
    相关资源
    最近更新 更多