Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine when Subject has no subscribers

I want to create a broadcast system using PublishSubject, a background task will poll some endpoint and broadcast the result periodically using this Subject. I would like to start the polling when the first subscriber subscribes to the Subject, and stop the polling when there are no more subscribers. If a new subscriber subscribes, polling should resume.

The only function I see that is somewhat related is hasObservers() but it doesn't quite fit my needs, I would like to have callbacks for subscription and unsubscription - on the former I would start polling if not stated, and on the latter I would stop polling if there are no more subscribers; how could this be achieved?

like image 465
Francesc Avatar asked Jun 14 '17 04:06

Francesc


1 Answers

You could create a wrapper around a subject that would keep count, but sounds like your problem could be solved with a ConnectableObservable. Consider this:

Observable<PollData> pollData = Observable.interval(1, TimeUnit.SECONDS)
                         .flatMap(i -> api.pollData())
                         .share();

Using the share() operator makes that observable become a ConnectableObservable that will start when the first observer subscribes to it, share all emissions with subsequent subscriptions, and automatically stop when it's last observer unsubscribes. Read more about it here.

like image 193
Habib Okanla Avatar answered Sep 30 '22 16:09

Habib Okanla