是否必须将 Rxlifecycle 与 android-arch-lifecycle 组件一起使用?

is it nessary to use Rxlifecycle with android-arch-lifecycle component?

如果应用中使用了android-arch-lifecycle组件,是否需要使用Rxlifecycle?还是 Rxlifecycle 是多余的? 或者如果我使用了 Rxlifecycle 和 RxJava,是否需要使用 android-arch-lifecycle 组件?

我相信,如果您不使用 android 架构组件 ViewModel,两个库将是相同的。

使用 ViewModel,您可以在设备旋转时阻止数据准备,这意味着 ViewModel 保留在内存中,即使 activity 必须重新启动以响应设备旋转。

我认为 RxLifecycle 库中不存在这样的组件。

不,您不需要使用 RxLifecycle,但如果您使用 RxJava,使用 RxLifecycle 可能会有用。

如果你使用 RxJava,你必须自己关心订阅和取消订阅。新机器人 LiveData (which is similar to the Rx Observables) does this itself by using the android-arch-lifecycle. If you also want a lifecycle awareness in RxJava you can use RxLifecycle。如他们的 Github 页面所述,RxLifecylce 需要一个 Lifecycle Provider。生成 Lifecycle Provider 的一种解决方案是使用 android-arch-lifecycle.

public class MyActivity extends LifecycleActivity {
private final LifecycleProvider<Lifecycle.Event> provider
    = AndroidLifecycle.createLifecycleProvider(this);

@Override
public void onResume() {
    super.onResume();
    myObservable
        .compose(provider.bindToLifecycle())
        .subscribe();
}

编辑:RxLifecycle在某些情况下可能会出现问题,这就是为什么创建者建议使用AutoDispose or handle subscrption manually instead. He describes the problems in this post