我没有从Android架构组件中获得在Android和LiveData中使用RxJava的理由。如果以代码的形式解释用例和两者之间的差异,以及解释两者之间差异的示例示例,将会非常有帮助。


当前回答

关于最初的问题,RxJava和LiveData都能很好地互补。

LiveData在ViewModel层上表现出色,它与Android生命周期和ViewModel紧密集成。RxJava在转换方面提供了更多的功能(正如@Bob Dalgleish所提到的)。

目前,我们在数据源和存储库层使用RxJava,并在ViewModels中转换为LiveData(使用LiveDataReactiveStreams)(在将数据暴露给活动/片段之前)-非常满意这种方法。

其他回答

LiveData部分等于Rx Subject或SharedRxObservable LiveData管理订阅的生命周期,但Rx主题 订阅应该手动创建和处理 LiveData没有终止状态,但Rx Subject有OnError 和oncomplete

LiveData只是数据持有者而已。我们也可以说LiveData是具有生命周期意识的消费者。强烈建议LiveData了解生命周期的概念和相关对象LifeCycleOwner/ lifecycle,您可以获得业务逻辑的转换和流功能,以及UI的生命周期感知操作。

Rx是一个强大的工具,能够以优雅的声明式风格解决问题。它处理业务端选项或服务Api操作

我的简单回答是不要使用RxJava。这是一种过于复杂和滥用的方式。对于所有使用RxJava的项目来说,它们都很难维护和调试。RxJava是异步的,使用线程来分派请求,一般来说这是完全不必要的,如果需要的话,Kotlin协程在99%的情况下做得更好。

事实上,LiveData与RxJava并不是本质上不同的工具,那么当RxJava可以通过将所有订阅的可观察对象存储在CompositeDispoable对象中,然后将它们处理在Activity的onDestroy()或Fragment的onDestroyView()中,只使用一行代码时,为什么要将它作为架构组件引入?

通过使用RxJava构建一个电影搜索应用程序,然后在这里使用LiveData,我已经完全回答了这个问题。

But in short, yes, it could, but that would need first overriding the relevant lifecycle methods besides having the basic lifecycle knowledge. This still might not make sense for some, but the fact is that according to one of the Jetpack sessions in Google I/O 2018 many developers find lifecycle management complex. The crash errors arising from not handling lifecycle dependence might be another sign that some developers, even if knowledgable of lifecycle, forget to take care of that in every Activity / Fragment they use in their app. In large apps this could become an issue, notwithstanding the negative effect it could have on productivity.

The bottom line is that by introducing LiveData , larger number of developers are expected to adopt MVVM without even having to understand the lifecycle management, memory leak and crash. Even though I have no doubt that LiveData is not comparable with RxJava in terms of capabilities and the power it gives to developers, reactive programming and RxJava is a hard-to-understand concept and tool for many. On the other side, I do not think LiveData is meant to be a replacement for RxJava–it simply cannot–but a very simple tool for handling a controversial widespread issue experienced by many developers.

**更新** 我在这里添加了一篇新文章,解释了滥用LiveData会导致意想不到的结果。RxJava可以在这些情况下发挥作用


比较LiveData和RxJava就像比较苹果和水果沙拉。

比较LiveData和contenttobserver,你是在比较苹果和苹果。LiveData有效地替代了contenttobserver的生命周期。

将RxJava与AsyncTask或任何其他线程工具进行比较,就像将水果沙拉与橙子进行比较一样,因为RxJava帮助的不仅仅是线程。