UtopiaLtd
UtopiaLtd

Reputation: 2590

Managing Shared Unsubscribing in SignalR and Rx

In our client application, we send and receive realtime events through SignalR.Client. Subscribing to events from the server is done through SignalR. In most cases, a subscribe event is sent to the SignalR hub via the SignalR client, and then using Reactive Extensions, the part of the application that would respond to such an event subscribes to the proper IObservable.

However, we now have a few cases where the same observable shares multiple observers. Disposing each internal subscription to the observable goes along fine, but I'd like to unsubscribe from receiving the given event on the server after the last observer is disposed. I've thought about just using separate connections for all these subscriptions, but in this particular network environment, there's a considerable delay before the connection becomes active.

As an example, a client application has components A, B, and C that all want to attach to SomeEvent being received from the server. Once any one of them becomes active, if it is first to do so, the application should subscribe to the event on the remote SignalR hub. When ANY of them becomes active, it should internally subscribe using Rx to the relevant observable from the observable collection we've already implemented (adding one if one doesn't already exist). When A, B, or C becomes inactive, it should obviously dispose of its IDisposable subscription. It should also unsubscribe from the SignalR hub server if it is the last one left.

Tl;dr: I would like to do a managed unsubscribe to see if the departing observer is the last one and only unsubscribing on the server hub at that point. Is there an effective way to count the number of "living" observers of an IObservable? Or an otherwise better method of implementing all of this? Much thanks!

Upvotes: 1

Views: 1136

Answers (1)

Gideon Engelberth
Gideon Engelberth

Reputation: 6155

.Publish().RefCount() does exactly what you are describing. Just make sure you use the same observable for each subscription or the ref counting won't work.

Upvotes: 2

Related Questions