如何使Kotlin协程函数不异步?

2fjabf4q  于 2022-12-30  发布在  Kotlin
关注(0)|答案(1)|浏览(116)

目前,我正在对2到3个不同的API进行API调用,其中第二个API调用依赖于第一个API调用的数据。然而,编译器甚至在第一个函数完成之前就调用了第二个函数,从而导致错误。我如何才能在第一个函数完成之后才调用第二个函数呢?谢谢

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

        }
    }
kmynzznz

kmynzznz1#

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

还有另一个函数async,无论函数被调用到哪里,它都返回结果。

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

相关问题