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