fun returnValue(): Int {
viewModelScope.launch {
return 1 // Something like this
}
}
我想在上述的viewModelScope中返回一些值。我不希望我的功能被暂停。我该如何实现?
您可以尝试这个
suspend fun returnValue(): Int {
suspendCoroutine<Int> { cont ->
viewModelScope.launch {
cont.resume(1)
}
}
}
如果returnValue()
无法暂停功能,则基本上只有两个选项:
Deferred<Int>
,然后让调用方负责稍后处理返回值。身体变成:fun returnValue(): Deferred<Int> = viewModelScope.async {
return@async 1
}
fun returnValue(): Int {
return runBlocking(viewModelScope.coroutineContext) {
return@runBlocking 1
}
}