简体   繁体   English

没有订阅者时如何暂停 shareReplay

[英]How do I pause shareReplay when there are no subscribers

For example:例如:

const s = rxjs.interval(2000).pipe(tap(console.log), shareReplay(1))
const b = s.subscribe(v => {})
// wait, console will begin output 0, 1, 2, 3, ...
b.unsubscribe()
// console will continue output 4, 5, 6, 7, ...

I want my stream paused when there are no subscribers to save CPU usage.当没有订阅者以节省 CPU 使用率时,我希望我的流暂停。

How do I pause the stream when there are no subscribers ?没有订阅者时如何暂停流?

The goal is to let multiple subscribers share a single stream.目标是让多个订阅者共享一个流。

  • When the first subscriber comes, the stream will start with an initial value and provide data periodically.当第一个订阅者到来时,流将以初始值开始并定期提供数据。
  • When a new subscriber comes, it will get the most recently value in the stream.当新订阅者到来时,它将获得流中的最新值。
  • When all subscriber gone, the data stream can be closed safely, next one comes will be treated as first one.当所有订阅者都离开时,数据流可以安全关闭,下一个将被视为第一个。

You'll need a multicast to share your data via ReplaySubject , with refCount to keep track of subscribers count.您需要一个multicast来通过ReplaySubject共享您的数据,并使用refCount来跟踪订阅者数量。

const s = rxjs.interval(2000).pipe(
  tap(console.log), 
  multicast(() => new ReplaySubject(1)),
  refCount()
);

const b = s.subscribe(v => {})

setTimeout(()=>{
  b.unsubscribe()
}, 5000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM