android - Mediator LiveData的addSource onChange回调是默认在主线程执行的吗?

标签 android kotlin android-livedata

来自文档:

addSource (LiveData source, Observer onChanged)

Starts to listen the given source LiveData, onChanged observer will be called when source value was changed.

onChanged callback will be called only when this MediatorLiveData is active.

If the given LiveData is already added as a source but with a different Observer, IllegalArgumentException will be thrown.

从源码来看,addSource函数总是在主线程执行。

@MainThread
public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) ...

这是否意味着提供给 addSource 方法的回调也在主线程上运行?

我想了解这一点,因为我想在回调中执行 setValue 并且 setValue 需要在主线程上运行。

我想做这样的事情:

viewState.addSource(someLiveData) { networkResourceResult ->
    viewState.value = currentViewState().copy(showLoadingSpinner = networkResource.status)
}

那么这样做安全吗?

最佳答案

您应该使用 postValue() 方法从工作线程设置值

You must call the setValue(T) method to update the LiveData object from the main thread. If the code is executed in a worker thread, you can use the postValue(T) method instead to update the LiveData object.

翻看Update LiveData objects段落

关于android - Mediator LiveData的addSource onChange回调是默认在主线程执行的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56942527/

相关文章:

android - 谷歌地图插件在显示时会导致 Flutter 应用程序崩溃

generics - Kotlin:返回泛型类型的函数。如果我不知道应该返回哪种具体类型怎么办?

android - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

hibernate - hibernate 并将@GeneratedValue与CockroachDB一起使用会导致SQLGrammarException

java - 改造、实时数据适配器、使响应类包装器通用?

android - 是否可以将两个 LiveData 做成一个 LiveData?

android - LiveData 到 Observable 转换使用 RxJava

java - 如何修复不同语言中出现的 setError 消息?

java - 使用 AsyncTask 无法正确执行多部分实体

android - 将 ARCore 1.1.0 与 NativeActivity 结合使用并使用其他 IDE 进行构建 (Visual Studio 2015/2017)