Nin*_*420 5 android kotlin kotlin-android-extensions kotlin-coroutines
https://developer.android.com/topic/libraries/architecture/coroutines
Android coroutinesplusliveData文档指出,liveData如果我们想在实时数据函数中执行异步操作,我们可以使用builder 函数
val user: LiveData<User> = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
Run Code Online (Sandbox Code Playgroud)
val user: LiveData<Result> = liveData {
emit(Result.loading())
try {
emit(Result.success(fetchUser())
} catch(ioException: Exception) {
emit(Result.error(ioException))
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试安装lifecycle-viewmodel-ktx库,但找不到这个块。
它位于哪里?
尝试:
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01'
Run Code Online (Sandbox Code Playgroud)
该函数位于此处: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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1022 次 |
| 最近记录: |