我没有从Android架构组件中获得在Android和LiveData中使用RxJava的理由。如果以代码的形式解释用例和两者之间的差异,以及解释两者之间差异的示例示例,将会非常有帮助。
当前回答
LiveData和RxJava有很多不同之处:
LiveData is not a STREAM while in RxJava everything (literally everything) is a STREAM. LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. LiveData is synchronous, So you can't execute a chunk of code (network call, database manipulation etc.) asynchronously using just LiveData as you do with RxJava. What best you can do to exploit the most of this duo is to use RxJava for your business logic (network call, data manipulation etc, anything that happens in and beyond Repository) and use LiveData for your presentation layer. By this, you get transformation and stream capabilities for your business logic and lifecycle-aware operation for your UI. LiveData and RxJava compliment each other if used together. What I mean is, do everything with RxJava and at the end when you want to update UI, do something like the code given below to change your Observable into LiveData. So, your View (UI) observes to the LiveData in ViewModel where your LiveData is nothing but non-mutable MutableLiveData (or MutableLiveData is mutable LiveData). So the question here is, why should you even use LiveData at the first place? As you can see below in the code, you store your response from RxJava to MutableLiveData (or LiveData) and your LiveData is lifecycle-aware, so in a way, your data is lifecycle-aware. Now, just imagine the possibility when your data itself know when and when-not-to update the UI. LiveData doesn't have a history (just the current state). Hence, you shouldn't use LiveData for a chat application. When you use LiveData with RxJava you don't need stuff like MediatorLiveData, SwitchMap etc. They are stream control tools and RxJava is better at that by many times. See LiveData as a data holder thing and nothing else. We can also say LiveData is lifecycle-aware consumer.
public class RegistrationViewModel extends ViewModel {
Disposable disposable;
private RegistrationRepo registrationRepo;
private MutableLiveData<RegistrationResponse> modelMutableLiveData =
new MutableLiveData<>();
public RegistrationViewModel() {
}
public RegistrationViewModel(RegistrationRepo registrationRepo) {
this.registrationRepo = registrationRepo;
}
public void init(RegistrationModel registrationModel) {
disposable = registrationRepo.loginForUser(registrationModel)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Response<RegistrationResponse>>() {
@Override
public void accept(Response<RegistrationResponse>
registrationModelResponse) throws Exception {
modelMutableLiveData.setValue(registrationModelResponse.body());
}
});
}
public LiveData<RegistrationResponse> getModelLiveData() {
return modelMutableLiveData;
}
@Override
protected void onCleared() {
super.onCleared();
disposable.dispose();
}
}
其他回答
我的简单回答是不要使用RxJava。这是一种过于复杂和滥用的方式。对于所有使用RxJava的项目来说,它们都很难维护和调试。RxJava是异步的,使用线程来分派请求,一般来说这是完全不必要的,如果需要的话,Kotlin协程在99%的情况下做得更好。
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可以在这些情况下发挥作用
比较LiveData和RxJava就像比较苹果和水果沙拉。
比较LiveData和contenttobserver,你是在比较苹果和苹果。LiveData有效地替代了contenttobserver的生命周期。
将RxJava与AsyncTask或任何其他线程工具进行比较,就像将水果沙拉与橙子进行比较一样,因为RxJava帮助的不仅仅是线程。
LiveData部分等于Rx Subject或SharedRxObservable LiveData管理订阅的生命周期,但Rx主题 订阅应该手动创建和处理 LiveData没有终止状态,但Rx Subject有OnError 和oncomplete
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件