为 liveData kotlin builder 函数指定一个现有的 LiveData 对象

Specify an existing LiveData object for the liveData kotlin builder function

例如,我们可以使用 liveData 构建器函数 创建 一个 LiveData 对象:

var liveData: LiveData<String> = liveData(Dispatchers.IO) {
    delay(1000)
    emit ("hello")

    delay(1000)
    emit ("world")
}

这在 ViewModel 中很有用,我创建了一个 LiveData 对象,它在一行中从异步重函数接收多个数据值。

但是,如果我 已经有 一个 MutableLiveData 对象并且只想在那里 post 值,而不创建新的 LiveData 对象怎么办?我该怎么做?

我需要一种方法将多个值异步发送到 ViewModel 范围内的现有 MutableLiveData 对象中,以便在清除 ViewModel 时自动完成所有 运行 任务。

您可以 post 到从 viewModelScope 启动的协程中的 MutableLiveData。

private val myMutableLiveData = MutableLiveData<String>()

fun someFun() {
    viewModelScope.launch {
        myMutableLiveData.value = “Hello”
        delay(500L)
        myMutableLiveData.value = “World”

        myMutableLiveData.value = someSuspendFunctionRetriever()

        val result = withContext(Dispatchers.IO) {
            someBlockingCallRetriever()
        }
        myMutableLiveData.value = result

        // or use post() when not on Main dispatcher:
        withContext(Dispatchers.IO) {
            val result = someBlockingCallRetriever()
            myMutableLiveData.post(result)
        }
    }
}