如何将 Kotlin 的协程与集合结合使用

Luk*_*dot 3 kotlin kotlin-coroutines

我对 Kotlin 及其协程模块相当陌生,我正在尝试做一些起初对我来说似乎非常简单的事情。

我有一个函数(getCostlyList()如下),在经过一些昂贵的计算后返回一个列表。该方法被连续调用多次。然后所有这些调用都会合并到一个 Set 中。

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

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

我的目标是使用协程对这个昂贵的方法进行异步调用,但我在解决这个问题时遇到了困难。

And*_*ana 5

你可以写这样的东西:

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