我正在尝试使用livedata构建器函数。确实,它是如此易于使用,但实际上我不明白如何重新启动协程。在我的代码下面:

val topStoriesResult : LiveData<UIState<TopStoryWrapper>> = liveData(Dispatchers.IO) {
    topStoriesRepository.getTopStoriesSetWrapper().apply {
        emit(UIState.Loading)
        onFailure { emit(UIState.NoData) }
        onSuccess { emit(UIState.HasData(it)) }
    }
}

最佳答案

docs说,liveData构建器无法重新启动:



为了使代码运行几次,我建议您创建一个函数并在需要时调用它,例如在按钮上单击:

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)) }
        }
    }
}

要在viewModelScope类中使用MainViewModel,请向build.gradle文件添加依赖项:

10-08 03:45