android - 为什么要考虑在 RxJava 中使用 AndroidObservables

标签 android rx-java rx-android

据我了解AndroidObservable有助于确保:

  1. 订阅者总是在主线程上观察
  2. 当分离/停止 fragment/Activity 时,观察立即停止,框架相关组件(如 ui textview 等)不会更新。

但是,为了确保释放上下文(防止泄漏),我看到的大多数示例通常都说您无论如何都必须执行 .unsubscribe onDestroyView/onDestroy,这实际上会停止订阅,并阻止订阅者接收无论如何,这些更新。

所以我的问题是:

如果我通过 .observeOn(AndroidSchedulers.mainThread() 手动指示订阅应该发生在主线程上,那么使用 AndroidObservables 还有其他好处吗?

以下两种方法有什么区别吗?

_subscription1 = AndroidObservable.bindFragment(MyFragment.this, myCustomAwesomeObservable()) //
                           .subscribeOn(Schedulers.io()) //
                           .subscribe(...);


_subscription2 =  myCustomAwesomeObservable()
                           .subscribeOn(Schedulers.io()) //
                           .observeOn(AndroidSchedulers.mainThread()) //
                           .subscribe(...);


@Override
public void onDestroyView() {
    _subscription1.unsubscribe();
    _subscription2.unsubscribe();
    super.onDestroyView();
}

最佳答案

你是对的。 AndroidObservable.bindFragment 目前所做的是:

This helper will schedule the given sequence to be observed on the main UI thread and ensure that no notifications will be forwarded to the activity in case it is scheduled to finish.

-- part of the source code comment

因此,您使用哪种实现并没有真正的区别。

但是,使用 AndroidObservable 仍然是一个好主意,因为将来可能会添加其他功能。

关于android - 为什么要考虑在 RxJava 中使用 AndroidObservables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618496/

相关文章:

java - 如何将 zip() 函数中的异常传递给订阅者

android - 获取 RxJava Observable 的当前值

android - WebSocket 和 Rx Java

Java - 日期模式匹配

android - 如何在 android 中为列表适配器使用 Notifydatasetchanged

javascript - 在网站中添加 Whatsapp 和其他通讯工具的共享(联系)按钮

android - 如果 GoogleCredential 已过期,如何检查它

java - RX Java 2 顺序处理契约(Contract)

java - 使用RxJava异步调用多个同步任务

java - RxJava2 中一次从列表中取出 n 个元素