ZakTaccardi ZakTaccardi - 1 month ago 6
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

Observable<Void>
that:


  • registers some
    BroadcastReceivers
    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
    BroadcastReceivers
    twice)



How do I accomplish this?

Answer

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 https://github.com/JakeWharton/RxReplayingShare - this caches the latest value while still unsubscribing from the source when it has no subscribers.

Comments