Reuse subscriber

此生再无相见时 提交于 2019-12-23 12:47:25

问题


In RxJava I have a Subscriber object wich I subscribe on a Observable. Later on (some time after onComplete() has been invoked) I create a new Observable and subscribe with the same Subscriber instance used before. However, that seems not work. Is a subscriber not reusable?

Example:

class Loader extends Subscriber<T> {

   public void load(){
       Observable.just("Foo").subscribe(this);
   }

   public void onComplete(){
     // update UI
   }

}

In my code I would like to instantiate a Loader once, and call load() multiple time, for instance after the user clicks on a refresh button ...


回答1:


You cannot reuse Subscriber, because it implements Subscription, which has an isUnsubscribed field which, once set to true, will never become false again, so Subscription is not reusable.

Observer, on the other hand, does not contain any information about the subscription status, so you can reuse it. Each time you subscribe an Observer to an Observable, the RxJava implementation will wrap it inside a new Subscriber for you.




回答2:


Use Observable::concat to create an Observable that emits the items from several Observables in sequence. Subscribe that.



来源:https://stackoverflow.com/questions/29415522/reuse-subscriber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!