为什么 LiveData 有一个单独的 MutableLiveData 子类? [英] Why there's a separate MutableLiveData subclass of LiveData?
问题描述
看起来 MutableLiveData
与 LiveData
的区别仅在于创建了 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 开发者文档,你可以看到 LiveData
, setValue()
&postValue()
方法不是公开的.
In LiveData - Android Developer Documentation, you can see that for LiveData
, setValue()
& postValue()
methods are not public.
然而,在 MutableLiveData - Android 开发者文档中,您可以看到也就是说,MutableLiveData
在内部扩展了 LiveData
并且 LiveData
的两个魔法方法在此公开可用,它们是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
是不可变的.MutableLiveData
是 LiveData
,它是 可变的 &线程安全.
So, LiveData
is immutable. MutableLiveData
is LiveData
which is mutable & thread-safe.
这篇关于为什么 LiveData 有一个单独的 MutableLiveData 子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!