簡體   English   中英

Kotlin 協程不執行多個掛起函數

[英]Kotlin Coroutine doesn't execute multiple suspend functions

我有一個簡單的掛起函數序列(在 Android Kotlin 中),我想按順序運行(一旦第一個完成,然后運行第二個。)

我嘗試做一些像這樣合乎情理的事情:

class SomeService {

    init {

        GlobalScope.launch(Dispatchers.IO) {
            firstSuspendFunction()
            secondSuspendFunction()
        }
    }

}

但是,只有第一個運行,第二個永遠不會執行。 為什么?

編輯:我試圖排除一些可能的問題,似乎起作用的是首先完全清空 function(空體)!

問題是我的 firstFunction 實際上有效,它有這樣的東西:

private suspend fun firstSuspendFunction() {
    localProtoDataStore.preferences.collect {
        someDataList.addAll(it.preferenceData)
    }
}

如果第一次暫停 function 已經完成,是否會以某種方式launch永遠不知道?

我假設localProtoDataStore.preferences返回一個Flow並且它看起來是無限的,因為它會監聽偏好的變化。 在此類Flow上調用collect()將暫停任何 function 直到收集完成(但它從未完成,因為Flow是無限的)或執行協程的CoroutineScope被取消。

因此,要執行第二個 function,您有幾個選擇。 例如,您只能從Flow中獲取一個值:

private suspend fun firstSuspendFunction() {
    localProtoDataStore.preferences.firstOrNull {
        someDataList.addAll(it.preferenceData)
    }
}

或者您可以擺脫在firstSuspendFunction()中使用Flow並只檢索首選項中的當前數據:

private suspend fun firstSuspendFunction() {
    val data = localProtoDataStore.preferences.get() // I don't know the exact name of the function, but the idea is clear
    someDataList.addAll(data)
}

或者您可以啟動另一個協程來從Flow收集數據:

scope.launch(Dispatchers.IO) {
    launch {
        firstSuspendFunction()
    }
    secondSuspendFunction()
}

為父協程中的每個function調用啟動新的協程,以便它們可以單獨從 Flow 收集數據,而不會陷入父協程的暫停狀態 例如,在您的情況下:

GlobalScope.launch(Dispatchers.IO) {
    launch { 
        firstSuspendFunction()
    }
    launch { 
        secondSuspendFunction()
    }
    ....
}

暫無
暫無

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

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