Rxandroid What's the difference between SubscribeOn and ObserveOn

后端 未结 5 1998
逝去的感伤
逝去的感伤 2020-12-23 09:09

I am just learning Rx-java and Rxandroid2 and I am just confused what is the major difference between in SubscribeOn and ObserveOn.

5条回答
  •  生来不讨喜
    2020-12-23 09:57

    If someone finds rx java description hard to understand (as me for example), here is pure java explanation:

    subscribeOn()

    Observable.just("something")
      .subscribeOn(Schedulers.newThread())
      .subscribe(...);
    

    Is equivalent of:

    Observable observable = Observable.just("something");
    new Thread(() -> observable.subscribe(...)).start();
    

    Because Observable emits values on subscribe() and here subscribe() goes in the separate thread, the values are also emitted in the same thread as subscribe(). This is why it works "upstream" (influences the thread for the previous operations) and "downstream".

    observeOn()

    Observable.just("something")
      .observeOn(Schedulers.newThread())
      .subscribe(...);
    

    Is equivalent of:

    Observable observable = Observable.just("something")
      .subscribe(it -> new Thread(() -> ...).start());
    

    Here Observable emits values in the main thread, only the listener method is executed in the separate thread.

提交回复
热议问题