簡體   English   中英

如何使 Kotlin 協程 function 不異步?

[英]How to make a Kotlin Coroutine function not asynchronous?

目前,我正在對 2 到 3 個不同的 API 進行 API 調用,其中第二個 API 調用依賴於第一個調用的數據。 但是,編譯器甚至在第一個 function 完成之前調用第二個 function,從而導致錯誤。 如何在第一個完成后才能撥打第二個 function? 謝謝

/**
     *  Function to get Bus Timings depending on Bus Service No. or Bus Stop Code
     */
    fun determineUserQuery(userInput: String) {
        // Determine if User Provided a Bus Service No. or Bus Stop Code
        val userInputResult = determineBusServiceorStop(userInput)
        viewModelScope.launch {
            if (userInputResult.busServiceBool) {
                busServiceBoolUiState = true
                coroutineScope {
                    // Provided Bus Service, Need get Route first
                    getBusRoutes(targetBusService = userInputResult.busServiceNo)
                }
                delay(2000)
                // Get the Bus Timing for Each Route
                Log.d("debug2", "String ${_busRouteUiState.value.busRouteArray}")
                getMultipleBusTimings(busRoutes = _busRouteUiState.value.busRouteArray)
            }
            else {
                // Provided Bus Stop Code
                coroutineScope {
                    launch {
                        getBusStopNames(targetBusStopCode = userInputResult.busStopCode?.toInt())
                    }
                    launch {
                        getBusTimings(userInput = userInputResult.busStopCode)
                    }
                }
            }


        }
    }

CoroutineScope 的 Launcher 中有一個方法join() ,它是一個完成監聽器。

CoroutineScope(Dispatchers.Main).launch {
    CoroutineScope(Dispatchers.IO).launch {
        // Your 1st Task
        ...
    }.join()
    CoroutineScope(Dispatchers.IO).launch {
        // Your 2nd Task
        ...
    }.join()
    CoroutineScope(Dispatchers.IO).launch {
       // Your 3rd Task
        ...
    }.join()
}

還有另一個 function async也會在 function 被調用的任何地方返回結果.. await()

CoroutineScope(Dispatchers.Main).launch {
    // Your 1st Task
    val result1 = CoroutineScope(Dispatchers.IO).async {
        val v1 = "Hello!"
        v1
    }
    // Your 2nd Task
    val result2 = CoroutineScope(Dispatchers.IO).async {
        val v2 = result1.await() + " Android"
        v2
    }
    // Your 3rd Task
    val result3 = CoroutineScope(Dispatchers.IO).async {
        val v3 = result2.await() + " Developer"
    }

    // execute all be calling following
    result3.await()
}

暫無
暫無

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

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