为什么有单独的LiveData子类MutableLiveData子类? [英] Why there's a separate MutableLiveData subclass of LiveData?

查看:167
本文介绍了为什么有单独的LiveData子类MutableLiveData子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来MutableLiveDataLiveData的不同之处仅在于公开了setValue()postValue()方法,而在LiveData中它们受到了保护.

It looks like MutableLiveData differs from LiveData only by making the setValue() and postValue() methods public, whereas in LiveData they are protected.

有什么理由为此更改创建单独的类,而不是简单地将这些方法定义为LiveData本身的公共方法?

What are some reasons to make a separate class for this change and not simply define those methods as public in the LiveData itself?

通常来说,这样的继承形式(增加某些方法的可见性是唯一的变化)是一种众所周知的做法吗?在某些情况下它可能有用(假设我们可以访问所有代码)?

Generally speaking, is such a form of inheritance (increasing the visibility of certain methods being the only change) a well-known practice and what are some scenarios where it may be useful (assuming we have access to all the code)?

推荐答案

LiveData中-Android开发者文档,您可以看到LiveDatasetValue()& postValue()方法不是公开的.

In LiveData - Android Developer Documentation, you can see that for LiveData, setValue() & postValue() methods are not public.

MutableLiveData-Android开发人员文档中,您可以看到即MutableLiveData在内部扩展LiveData,并且LiveData的两个魔术方法也可以在 public 中使用,它们是setValue()& postValue().

Whereas, in MutableLiveData - Android Developer Documentation, you can see that, MutableLiveData extends LiveData internally and also the two magic methods of LiveData is publicly available in this and they are setValue() & postValue().

setValue():设置值并将其分发给所有活动的观察者,必须从主线程中调用.

setValue(): set the value and dispatch the value to all the active observers, must be called from main thread.

postValue():将任务发布到主线程以覆盖由setValue()设置的值,必须从后台线程中调用.

postValue() : post a task to main thread to override value set by setValue(), must be called from background thread.

因此,LiveData不可变的. MutableLiveDataLiveData,是可变& 线程安全.

So, LiveData is immutable. MutableLiveData is LiveData which is mutable & thread-safe.

这篇关于为什么有单独的LiveData子类MutableLiveData子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆