setValue()与&的区别MutableLiveData中的postValue() [英] Difference of setValue() & postValue() in MutableLiveData
问题描述
有两种方法可以更改MutableLiveData
的值.但是 setValue()
和& MutableLiveData
中的 postValue()
.
There are two ways that make change value of MutableLiveData
. But what is difference between setValue()
& postValue()
in MutableLiveData
.
我找不到相同的文档.
这是Android的类MutableLiveData
.
Here is class MutableLiveData
of Android.
package android.arch.lifecycle;
/**
* {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
*
* @param <T> The type of data hold by this instance
*/
@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
推荐答案
基于文档:
设置值.如果有活动的观察者,则该值为 派给他们.必须从主线程调用此方法.
Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.
将任务发布到主线程以设置给定值.如果您在主线程执行发布的任务之前多次调用此方法,则只会分派最后一个值.
Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.
总而言之,关键区别在于:
To summarize, the key difference would be:
setValue()
方法必须从主线程调用.但是,如果需要从后台线程设置值,则应使用postValue()
.
setValue()
method must be called from the main thread. But if you need set a value from a background thread, postValue()
should be used.
这篇关于setValue()与&的区别MutableLiveData中的postValue()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!