Search code examples
javarx-javarx-java2reactivex

What does share operator do in RxJava? When should I use it?


I know that share() is a replacement of publish().refCount(). Then from the RxJava wiki:

Observable.publish( ) — represents an Observable as a Connectable Observable ConnectableObservable.refCount( ) — makes a Connectable Observable behave like an ordinary Observable

This make me confused. If after publish().refCount(), it just behave like an ordinary Observable, why should I use it, how does this api make sense?


Solution

  • You're right - Observable.share is just a shortcut for publish().refCount(). I think that description you have quoted above is not entirely clear as ConnectedObservable.refCount does a little bit more :)

    If you transform your Observable to ConnectableObservable - it will not emit items (even if something is subscribed) unless explicitly called ConnectableObservable.connect - it basically defers execution of subscribe method and prevents from executing it multiple times for every subscriber. This technique is often used to make sure that all subscribers are subscribed before observable starts emitting items (in other words - after everyone has subscribed - connect() method is called).

    If you have more than one subscriber (what often happens), you have to handle their subscriptions and unsubscriptions and this is where things are getting tricky. This is why refCount() was introduced. This operator returns new Observable, keeps track of how many subscribers are subscribed to it and stays connected as long as there is at least one subscription. It will also automatically connect when the first subscriber appears.

    PS. I'm learning how to use RxJava, if I am wrong - please point it out!