Dims
Dims

Reputation: 51039

How to subscribe several subscribers to Observable or Flowable?

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?

Upvotes: 1

Views: 3816

Answers (1)

Yaroslav Stavnichiy
Yaroslav Stavnichiy

Reputation: 21446

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.

Upvotes: 3

Related Questions