来自文档:
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 theLiveData
object from the main thread. If the code is executed in a worker thread, you can use thepostValue(T)
method instead to update theLiveData
object.
关于android - Mediator LiveData的addSource onChange回调是默认在主线程执行的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56942527/