簡體   English   中英

暫停kotlin coroutine異步子功能

[英]Suspend kotlin coroutine async subfunction

我有一個異步CoroutineScope ,其中可以(通過條件)調用子函數,該子函數在異步Unit返回其結果

如何等待返回的結果並將其返回到異步Unit 因此等待子功能對Unit的調用。

例:

GlobalScope.launch {
    var value: Int = 0
    if (condition) {
        // the subFunction has a Unit<Int> as return type
        subFunction() { result ->
            value = result
        }
    }
    Log.v("LOGTAG", value.toString())
}

如何在繼續代碼之前等待subFunction功能完成執行,或者直接將結果值分配給變量?

subFunction 不能suspend函數,但它可以嵌入到輔助函數中。

(代碼必須在Android環境中運行)

您可以這樣做,將回調轉換為暫停功能

GlobalScope.launch {
    var value: Int = 0
    if (condition) {
        // the subFunction has a Unit<Int> as return type
        value = subFunctionSuspend()
    }
    Log.v("LOGTAG", value.toString())
}

suspend fun subFunctionSuspend() = suspendCoroutine { cont ->
    subFunction() { result ->
        cont.resume(result)
    }
} 

不太好但是有渠道的工作解決方案:

    GlobalScope.launch {
        val channel = Channel<Int>()
        if (condition) {
            // the subFunction has a Unit<Int> as return type
            subFunction() { result ->
                GlobalScope.launch {
                    channel.send(result)
                    channel.close()
                }
            }
        }
        for (i in channel) {
            println(i)
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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