Lukas Cardot
Lukas Cardot

Reputation: 205

How to use Kotlin's coroutines with collections

I'm fairly new to Kotlin and its coroutines module, and I'm trying to do something that seemed pretty simple to me at first.

I have a function (the getCostlyList() below) that returns a List after some costly computation. This method is called multiple time sequentially. All these calls are then merged into a Set.

    private fun myFun(): Set<Int> {
        return (1..10)
                .flatMap { getCostlyList() }
                .toSet()
    }

    private fun getCostlyList(): List<Int> {
        // omitting costly code here...
        return listOf(...)
    }

My goal would be to use coroutines to make these calls to this costly method asynchronously, but I am having trouble wrapping my head around this issue.

Upvotes: 3

Views: 757

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8432

you can write something like this:

private suspend fun myFun(): Set<Int> = coroutineScope {
    (1..10)
        .map { async { getCostlyList() } }
        .awaitAll()
        .flatten()
        .toSet()
}

Upvotes: 5

Related Questions