How to subscribe several subscribers to Observable

2020-04-20 20:56发布

问题:

In Hello World example there is one subscriber

   public static void main(String[] args) {
      Flowable.just("Hello world").subscribe(System.out::println);
   }

How to make two or more?

回答1:

You can subscribe multiple subsctibers to any observable/flowable. Just repeat subscribe call as many times as you need.

Flowable<String> source = Flowable.just("Hello world");
source.subscribe(System.out::println);
source.subscribe(System.out::println);
...

There is difference in hot and cold observables in the way they handle such multiple subscriptions.

Cold observables/flowables re-request items from source for every new subscriber. For example, Flowable.fromCallable(c) will invoke c every time it is subscribed to.

Hot observables/flowables share same source subscription with all subscribers, i.e. they do not request new items from source for every new subscriber. New items get propagated to all currently subscribed subscribers.