ZakTaccardi ZakTaccardi - 1 year ago 64
Android Question

How to have subscription side effects of source observable trigger only when the subscriber count changes from 0 to 1 or from 1 to 0

I have a source


  • registers some
    when its subscribed to

  • unregisters them when unsubscribed from.

  • I only want subscription side effects to occur when the subscriber count increases from 0 to 1, or from 1 back to 0.

  • Adding a 2nd subscriber to this observable should have no effect on the source observable (I don't want to register the

How do I accomplish this?

Answer Source

The .share() operator

Observable<Void> src = ...;
Observable<Void> shareable = src
    .doOnSubscribe(() -> {...})
    .doOnUnsubscribe(() -> {...})
    .share()  //<------------ or publish.refcount

Note: There's a race condition here for additional subscribers. if you are expecting to receive an event when you subscribe initially for every subscriber, use .replayingShare() from - this caches the latest value while still unsubscribing from the source when it has no subscribers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download