我如何在Android的生命周期感知协程范围中返回函数值?

问题描述 投票:0回答:2
fun returnValue(): Int {
    viewModelScope.launch { 
        return 1 // Something like this
    }
}

我想在上述的viewModelScope中返回一些值。我不希望我的功能被暂停。我该如何实现?

android android-studio android-asynctask android-lifecycle kotlin-coroutines
2个回答
0
投票

您可以尝试这个

suspend fun returnValue(): Int {
    suspendCoroutine<Int> { cont ->
        viewModelScope.launch {
            cont.resume(1)
        }
    }
}

0
投票

如果returnValue()无法暂停功能,则基本上只有两个选项:

  1. 将返回类型转换为Deferred<Int>,然后让调用方负责稍后处理返回值。身体变成:
fun returnValue(): Deferred<Int> = viewModelScope.async {
    return@async 1
}
  1. 阻塞线程,直到值可用为止:
fun returnValue(): Int {
    return runBlocking(viewModelScope.coroutineContext) {
        return@runBlocking 1
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.