![](/img/trans.png)
[英]Android How Lifecycle-Aware Components Detect Configuration Change inside ViewModel
[英]How do I return function value in lifecycle-aware coroutine scope in Android?
fun returnValue(): Int {
viewModelScope.launch {
return 1 // Something like this
}
}
我想在上面的 viewModelScope 中返回一些值。 我不希望我的功能被挂起。 我该如何做到这一点?
如果returnValue()
不能挂起函数,基本上只有两种选择:
Deferred<Int>
并让调用者负责稍后处理返回值。 身体变成:fun returnValue(): Deferred<Int> = viewModelScope.async {
return@async 1
}
fun returnValue(): Int {
return runBlocking(viewModelScope.coroutineContext) {
return@runBlocking 1
}
}
你可以试试这个
suspend fun returnValue(): Int {
suspendCoroutine<Int> { cont ->
viewModelScope.launch {
cont.resume(1)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.