![](/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.