android - MutableLiveData 中 setValue() 和 postValue() 的区别

标签 android android-livedata mutablelivedata

MutableLiveData 的改变值有两种方式。但是 MutableLiveData 中的 setValue()postValue() 有什么区别。

我找不到相同的文档。

这里是Android的MutableLiveData类。

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.

总而言之,主要区别在于:

setValue() 方法必须从主线程调用。但是如果你需要从后台线程设置一个值,应该使用 postValue()

关于android - MutableLiveData 中 setValue() 和 postValue() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51299641/

相关文章:

java - 尝试从 JSON 数组将数据插入数据库

android - 在 NestedScrollView 中使用 RecyclerView 时性能不佳

android - 带有 Viewpager2-Fragments 的实时数据

android - 使用 LiveData 的 JUnit5 测试不执行订阅者的回调

android - MutableLiveData 未在 UI 中更新

android - 动态添加相对布局到线性布局

java - 在 AndroidManifest.xml 中声明 Activity 以使用 Intent

android - 建议在 View 模型 android kotlin 的实时数据中使用 getter 或 equals

android - 有没有更好的方法将私有(private) MutableLiveData 公开为 ViewModel 的 LiveData。 [安卓、 Kotlin ]

机器人 : mutablelivedata change is not updating the UI