https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
h

Henri Gourvest

12/07/2023, 10:28 PM
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

kevin.cianfarini

12/07/2023, 10:39 PM
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

Henri Gourvest

12/07/2023, 10:47 PM
yes, I need to generate a sequence asyncronously. Thank you!
c

Casey Brooks

12/07/2023, 10:56 PM
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

Henri Gourvest

12/07/2023, 11:33 PM
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.
3 Views