我没有从Android架构组件中获得在Android和LiveData中使用RxJava的理由。如果以代码的形式解释用例和两者之间的差异,以及解释两者之间差异的示例示例,将会非常有帮助。
当前回答
我的简单回答是不要使用RxJava。这是一种过于复杂和滥用的方式。对于所有使用RxJava的项目来说,它们都很难维护和调试。RxJava是异步的,使用线程来分派请求,一般来说这是完全不必要的,如果需要的话,Kotlin协程在99%的情况下做得更好。
其他回答
LiveData是android架构组件的一个子集,由android团队开发。
对于活动数据和其他体系结构组件,内存泄漏和其他类似问题由体系结构组件处理。由于它是由android团队开发的,所以它是android最好的。他们还提供处理新版本Android的更新。
如果你只想在Android应用程序开发中使用,请使用Android架构组件。否则,如果你想使用其他Java应用程序,如web应用程序,桌面应用程序等,请使用RxJava
关于最初的问题,RxJava和LiveData都能很好地互补。
LiveData在ViewModel层上表现出色,它与Android生命周期和ViewModel紧密集成。RxJava在转换方面提供了更多的功能(正如@Bob Dalgleish所提到的)。
目前,我们在数据源和存储库层使用RxJava,并在ViewModels中转换为LiveData(使用LiveDataReactiveStreams)(在将数据暴露给活动/片段之前)-非常满意这种方法。
LiveData只是数据持有者而已。我们也可以说LiveData是具有生命周期意识的消费者。强烈建议LiveData了解生命周期的概念和相关对象LifeCycleOwner/ lifecycle,您可以获得业务逻辑的转换和流功能,以及UI的生命周期感知操作。
Rx是一个强大的工具,能够以优雅的声明式风格解决问题。它处理业务端选项或服务Api操作
事实上,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可以在这些情况下发挥作用
我的简单回答是不要使用RxJava。这是一种过于复杂和滥用的方式。对于所有使用RxJava的项目来说,它们都很难维护和调试。RxJava是异步的,使用线程来分派请求,一般来说这是完全不必要的,如果需要的话,Kotlin协程在99%的情况下做得更好。
推荐文章
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?
- androidviewpager与底部点