简体   繁体   中英

Kotlin coroutines runBlocking async

I'm new to coroutines and trying to leverage them to call a time consuming method a couple of times in less time

fun callAPI(idList: Collection<String>): List<String> {
       
        val storedIds = mutableListOf<String>()
        runBlocking {
             val ids = idList.map { data ->
                   async {timeConsumingMethod(data)}
                    }.map { it.await() }
                    storedIds.addAll(ids)

        }
        return storedIds
    }

I need all the calls to timeConsumingMethod to run in parallel, but i don't want callAPI to return until after all the timeConsumingMethods finish.

Running this i see the timeConsumingMethods are running synchronously

Can anyone give me a hand in understanding what mistake i'm missing?

You need to specify a dispatcher other than runBlocking 's default single thread dispatcher, or nothing can run in parallel.

Your code can also be rearranged a bit for clarity/conciseness.

fun callAPI(idList: Collection<String>): List<String> = runBlocking(Dispatchers.IO) {
    idList.map {
        async { timeConsumingMethod(it) }
    }.awaitAll()
}

If you are working with a UI that you don't want to freeze during the operation, you should consider making this a suspend function and responding to the results when they are ready, rather than using runBlocking .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM