android - 如何重新启动 livedata builder 功能?

标签 android kotlin android-livedata kotlin-coroutines

我正在尝试使用 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 and LiveData. The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive. If it is canceled before completion, it is restarted if the LiveData 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/

相关文章:

android - Fragments 和 Activity——我应该把我的应用程序逻辑放在哪里?

android - Firebase/Android - 经常失去数据库连接

Android 房间 rawquery 问题

viewmodel - Livedata与Rxjava

android - Imageview不显示圆角

android - 使用 Handler 从线程更新 UI 时出错

可选的 Kotlin 多平台支持

android - 如何在 Room 中插入具有一对多关系的实体

android - 使用 Retrofit 使用 LiveData 和 Repository 设置 ViewModel 的正确方法

安卓架构组件 : How is LiveData in the repository observed by a ViewModel