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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With