我正在尝试使用 livedata
构建器函数。确实,它非常易于使用,但实际上我无法理解如何重新启动协程。在我的代码部分下面:
val topStoriesResult : LiveData<UIState<TopStoryWrapper>> = liveData(Dispatchers.IO) {
topStoriesRepository.getTopStoriesSetWrapper().apply {
emit(UIState.Loading)
onFailure { emit(UIState.NoData) }
onSuccess { emit(UIState.HasData(it)) }
}
}
最佳答案
liveData
构建器无法重新启动,docs说:
The
liveData
building block serves as a structured concurrency primitive between coroutines andLiveData
. The code block starts executing whenLiveData
becomes active and is automatically canceled after a configurable timeout when theLiveData
becomes inactive. If it is canceled before completion, it is restarted if theLiveData
becomes active again. If it completed successfully in a previous run, it doesn't restart. Note that it is restarted only if canceled automatically. If the block is canceled for any other reason (e.g. throwing a CancelationException), it is not restarted.
为了让代码运行几次,我建议创建一个函数并在需要时调用它,例如点击按钮:
class MainViewModel : ViewModel() {
val topStoriesResult: LiveData<UIState<TopStoryWrapper>> = MutableLiveData<UIState<TopStoryWrapper>>()
fun loadTopStories() = viewModelScope.launch(Dispatchers.IO) { // start a coroutine
topStoriesRepository.getTopStoriesSetWrapper().apply {
val mutableLiveData = loginResponse as MutableLiveData
// post value to LiveData
mutableLiveData.postValue(UIState.Loading)
onFailure { mutableLiveData.postValue(UIState.NoData) }
onSuccess { mutableLiveData.postValue(UIState.HasData(it)) }
}
}
}
要在 MainViewModel
类中使用 viewModelScope
,请将依赖项添加到 build.gradle 文件:
final LIFECYCLE_VERSION = "2.2.0-rc03" // add most recent version
api "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION"
关于android - 如何重新启动 livedata builder 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274298/