本文介绍了重用订阅者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 RxJava 中,我有一个 Subscriber 对象,我订阅了一个 Observable.稍后(在调用 onComplete() 之后的一段时间)我创建了一个新的 Observable 并使用之前使用的相同 Subscriber 实例进行订阅.但是,这似乎行不通.订阅者不可重复使用吗?

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?

示例:

class Loader extends Subscriber<T> {

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

   public void onComplete(){
     // update UI
   }

}

在我的代码中,我想实例化一个 Loader,并多次调用 load(),例如在用户点击刷新按钮之后......

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 ...

推荐答案

你不能重用Subscriber,因为它实现了Subscription,它有一个isUn​​subscribed 字段,一旦设置为 true,将永远不会再次变为 false,因此 Subscription 不可重复使用.

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 不包含有关订阅状态的任何信息,因此您可以重复使用它.每次您将 Observer 订阅到 Observable 时,RxJava 实现都会为您将其包装在一个 new Subscriber 中.

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.

这篇关于重用订阅者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 06:24