簡體   English   中英

如何在 Android 的生命周期感知協程范圍內返回函數值?

[英]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()不能掛起函數,基本上只有兩種選擇:

  1. 將返回類型轉換為Deferred<Int>並讓調用者負責稍后處理返回值。 身體變成:
fun returnValue(): Deferred<Int> = viewModelScope.async {
    return@async 1
}
  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM