[英]How do I return function value in lifecycle-aware coroutine scope in Android?
fun returnValue(): Int {
viewModelScope.launch {
return 1 // Something like this
}
}
I want to return some value in a viewModelScope like the above.我想在上面的 viewModelScope 中返回一些值。 I don't want my function to be suspended function.
我不希望我的功能被挂起。 How do I achieve that?
我该如何做到这一点?
If returnValue()
cannot be suspended function, there are basically only two options:如果
returnValue()
不能挂起函数,基本上只有两种选择:
Deferred<Int>
and make the caller responsible for handling the return value at a later point.Deferred<Int>
并让调用者负责稍后处理返回值。 The body becomes:fun returnValue(): Deferred<Int> = viewModelScope.async {
return@async 1
}
fun returnValue(): Int {
return runBlocking(viewModelScope.coroutineContext) {
return@runBlocking 1
}
}
you can try this你可以试试这个
suspend fun returnValue(): Int {
suspendCoroutine<Int> { cont ->
viewModelScope.launch {
cont.resume(1)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.