首页 > 解决方案 > 如何在 Android 的生命周期感知协程范围内返回函数值?

问题描述

fun returnValue(): Int {
    viewModelScope.launch { 
        return 1 // Something like this
    }
}

我想在上面的 viewModelScope 中返回一些值。我不希望我的功能被挂起。我该如何做到这一点?

标签: androidandroid-studioandroid-asynctaskandroid-lifecyclekotlin-coroutines

解决方案


如果returnValue()不能挂起功能,基本上只有两种选择:

  1. 将返回类型转换为Deferred<Int>并让调用者负责稍后处理返回值。身体变成:
fun returnValue(): Deferred<Int> = viewModelScope.async {
    return@async 1
}
  1. 阻塞线程直到值可用:
fun returnValue(): Int {
    return runBlocking(viewModelScope.coroutineContext) {
        return@runBlocking 1
    }
}

推荐阅读