Hello, I'm still learning and I need to paralleliz...
# multiplatform
h
Hello, I'm still learning and I need to parallelize tasks and collect results without using the thread safe lists only available in Java. This is what I tried to do, it works, but is it the right way to do it in your opinion?
Copy code
suspend fun foo() = callbackFlow {
    coroutineScope {
        launch { 
            delay(100)
            channel.send(1)
        }
        launch {
            delay(100)
            channel.send(2)
        }
    }
    channel.close()
}
k
It kind of depends on your use case. If you are trying to generate a current, asynchronous sequence of elements this is exactly what you're supposed to do. If you're trying to just launch several asynchronous tasks concurrently you should look at the
coroutineScope
builder function.
h
yes, I need to generate a sequence asyncronously. Thank you!
c
Something like this might also be what you’re looking for, which is a bit easier to understand than managing a channel:
Copy code
suspend fun foo(): List<Int> = coroutineScope {
	listOf(
        async {
            delay(100)
            1
        },
        async {
            delay(100)
            2
        }
    ).awaitAll()
}
h
Interesting, I'm saving this idea for other scenarios. In the case I'm interested in, the number of elements in the list is not known and the tasks may fail.