setValue() & 的区别MutableLiveData 中的 postValue() [英] Difference of setValue() & postValue() in MutableLiveData

查看:49
本文介绍了setValue() & 的区别MutableLiveData 中的 postValue()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以改变MutableLiveData的值.但是 setValue() & 之间有什么区别?postValue()MutableLiveData 中.

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);
    }
}

推荐答案

基于文档:

setValue():

设置值.如果有活跃的观察者,该值将是派发给他们.这个方法必须从主线程调用.

Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.

postValue():

将任务发布到主线程以设置给定值.如果在主线程执行已发布的任务之前多次调用此方法,则只会调度最后一个值.

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() &amp; 的区别MutableLiveData 中的 postValue()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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