https://kotlinlang.org logo
Title
s

Simon Lin

12/14/2021, 6:34 AM
If I want the outputs and inputs have the same order but with different delays for each item. Is it efficient below?
fun foo() {
    viewModelScope.launch {
        val inputList = listOf("a", "b", "c")
        val deferredList = mutableListOf<Deferred<String>>()
        repeat(3) { index ->
            deferredList += async {
                delay((1L..10000L).random())
                inputList[index]
            }
        }
        val outputList = deferredList.map { it.await() } // a, b, c
    }
}
t

Tijl

12/14/2021, 7:05 AM
there is
awaitAll
for your
deferredList
though in this case it’s mostly a syntactic difference. In a more complex example it will be different (it will fail fast).
🙌 1
also consider
buildList
n

Nick Allen

12/14/2021, 4:48 PM
inputList.map { item -> async { doSuspendStuff(item) } }.awaitAll()
:also-yes: 1