Home > Net >  How to make a Kotlin Coroutine function not asynchronous?
How to make a Kotlin Coroutine function not asynchronous?

Time:01-02

Currently, I am making API calls to 2 to 3 different APIs, where the second API Call relies on data from the first. However, the compiler calls the 2nd function even before the first function is completed, causing an error. How can I call the 2nd function only after the first is done? Thank you

/**
     *  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)
                    }
                }
            }


        }
    }

CodePudding user response:

There is a method join() in CoroutineScope's Launcher, that is a completion listener.

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()
}

There's another function async that also returns result wherever the function it gets call.. 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()
}
  • Related