【发布时间】:2016-12-07 06:45:22
【问题描述】:
我有一个创建成本很高的 observable,所以我有 shared 它。但是,在某些情况下,所有订阅者都会取消订阅,然后立即(或在短暂延迟后)有新订阅者订阅。
实际的 observable 过于复杂,无法在此处复制,但为了论证:
const heavyObservable = Rx.Observable.create((observer) => {
console.log('I am expensive, avoid hitting this code');
return Rx.Observable
.interval(500) // these updates are cheap though!
.subscribe(observer)
.add(() => {
console.log('Cache has been destroyed, will have to be rebuild on next call');
});
});
我不想使用创建这个 observable 所涉及的昂贵代码。我想将断开连接延迟到 n 毫秒之后。有没有办法做到这一点?
const sharedObservable = heavyObservable
.publish()
// ideally I'm looking for a way to get refCount to wait for new
// subscribers for n ms before unsubscribing when refcount === 0
.refCount();
// calling subscribe here invokes heavyObservable which can take a bit of time
const subscription1 = sharedObservable.subscribe();
// log: I am expensive, avoid hitting this code
// second call is "free" - the underlying observable is reused
const subscription2 = sharedObservable.subscribe();
subscription1.unsubscribe();
subscription2.unsubscribe();
// calling subscribe again here invokes heavyObservable over again
const subscription3 = sharedObservable.subscribe();
// log: I am expensive, avoid hitting this code
【问题讨论】:
标签: typescript rxjs5