RxJava - When and why to use Observable.share()

后端 未结 2 1845
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 00:08

I\'ve seen patterns like this:

Observable nameChanges = nameDataSource.changes().share();

// One subscriber
autoUnsubscribe(nameChanges.subscribe(         


        
2条回答
  •  无人共我
    2021-02-02 00:39

    There are two kinds of Observables: cold and hot. Cold Observables start producing items when there is an Observer to them and they do it on an individual basis. Subscribing with multiple Observers will result in multiple runs of the same cold Observable. An example of this is an Observable that issues a network request.

    In contrast, a hot Observable can produce items with or without the presence of Observers. These Observables usually multicast the same items to all of their current Observers. An example of this is an Observable of button clicks.

    To turn a cold Observable into a hot one, you can use publish() which will make sure only a single subscription is established to the source Observable no matter how many Observers there are. Thus, the chain will now act as a hot multicasting Observable from the Observers' perspective.

    However, often it is not economic to keep an originally cold Observable running after all Observers of publish() have gone away, therefore the refCount() operator can be used to keep track of them and stop the source when there are no interesting parties left.

    If your source is already hot, you don't need share().

    Why is not share() the default behavior for all observables?

    Actually, this property is one of the important contributions of the modern reactive programming paradigm: the distinction of the hot and cold Observables.

    However, multicasting is expensive on itself because you have to keep track of the set of current Observers in order to notify them with new events, and this can lead to all sorts of logical race conditions to be defended against. A cold Observable is known to talk only to a single Observer so there is no need for the extra tracking overhead.

提交回复
热议问题