在哪里可以找到 liveData 构建块?

Where to find the liveData building block?

https://developer.android.com/topic/libraries/architecture/coroutines

Android coroutines 加上 liveData 文档指出我们可以使用 liveData 构建器函数以防我们想要在实时数据函数中执行异步操作

val user: LiveData<User> = liveData {
    val data = database.loadUser() // loadUser is a suspend function.
    emit(data)
}
val user: LiveData<Result> = liveData {
    emit(Result.loading())
    try {
        emit(Result.success(fetchUser())
    } catch(ioException: Exception) {
        emit(Result.error(ioException))
    }
}

我尝试安装 lifecycle-viewmodel-ktx 库但找不到这个块。

它位于哪里?

尝试:

implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01'

函数在这里: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/lifecycle/livedata/ktx/src/main/java/androidx/lifecycle/CoroutineLiveData.kt

并且(当前)定义为:

@UseExperimental(ExperimentalTypeInference::class)
fun <T> liveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT,
    @BuilderInference block: suspend LiveDataScope<T>.() -> Unit
): LiveData<T> = CoroutineLiveData(context, timeoutInMs, block)

我也有这个问题,我建议只添加他们建议的依赖项 here

问题是 Google 关于协程的 Android 文档没有明确提到这些 ktx 扩展(正如您在 link 中看到的那样)对能够获得提供 LiveDataScopeliveData 构建器。

不要错误地认为您可以使用较低版本,即 2.1.0,只需按照文档中明确指定的方式使用它,即 [=13= 中的 alpha/RC 版本].