跟踪 Observable 中的(数量)观察者? [英] Track the (number of) observers in an Observable?

查看:25
本文介绍了跟踪 Observable 中的(数量)观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表股票价格流的可观察对象.如果我的可观察序列上没有观察者,我希望能够与提供价格流的远程服务器断开连接,但在每个观察者都调用 Dispose() 之前,我不想这样做.然后以类似的方式,当第一个人调用 Subscribe 时,我想重新连接到远程服务器.

I have an observable which represents a stream of stock prices. If there are no observers on my observable sequence I'd like to be able to disconnect from the remote server that is supplying the stream of prices, but I don't want to do that until every observer has called Dispose(). Then in a similar fashion, when the first person calls Subscribe I'd like to reconnect to the remote server.

有没有办法算出有多少观察者在一个可观察的对象上调用了订阅?或者也许是一种了解观察者何时调用 Subscribe 或 Dispose 的方法?

Is there a way to figure out how many observers have called subscribe on an observable? Or perhaps a way to know when observers are calling Subscribe or Dispose?

推荐答案

我会简单地使用 RefCount/Publish.我总是觉得如果我在实施 IObservable,我就太努力了.

I would simply use RefCount / Publish. I always feel like if I'm implementing IObservable I'm working way too hard.

myColdObservable.Publish().RefCount();

这将使您的可观察对象在所有人断开连接后停止跳动.这是一个示例:

This will make your observable stop pulsing after everyone has disconnected. Here's a sample:

var coldObservable = Observable
    .Interval(TimeSpan.FromSeconds(1))
    .ObserveOn(Scheduler.TaskPool)
    .Select(_ => DoSomething());

var refCountObs = coldObservable.Publish().RefCount();

CompositeDisposable d = new CompositeDisposable();
d.Add(refCountObs.Subscribe(n => Console.WriteLine("First got: " + n)));
d.Add(refCountObs.Subscribe(n => Console.WriteLine("Second got: " + n)));
d.Add(refCountObs.Subscribe(n => Console.WriteLine("Third got: " + n)));

//Wait a bit for work to happen
System.Threading.Thread.Sleep(10000);

//Everyone unsubscribes
d.Dispose();

//Observe that DoSomething is not called.
System.Threading.Thread.Sleep(3000);

这不包括您实际上想知道订阅者的数量的情况,但我认为这符合您在没有订阅者的情况下停止工作的要求.

This does not cover the case where you actually want to know the number of subscribers, but I think this fits with your requirements of stopping work if there are no subscribers.

这篇关于跟踪 Observable 中的(数量)观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆