gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:19:53 26 4
gpt4 key购买 nike

来自文档:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com