How to subscribe several subscribers to Observable

2020-04-20 20:42发布

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条回答
来,给爷笑一个
2楼-- · 2020-04-20 21:37

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.

查看更多
登录 后发表回答