I have the following use case: I fire off a numbe...
# coroutines
I have the following use case: I fire off a number of REST calls to a very slow REST service, and want to return a filtered list of the results. So currently I'm creating a channel, launching each REST call in a coroutine, and writing the result of each to a channel. I then iterate through the channel, do a manual filter via an if statement, and add any filtered result to a mutable list. This feels a bit imperative to me - is there a better way of doing this that doesn't for example, rely on a mutable list and manual filtering ? Should I be using Flow and filters instead ?
Copy code
val output = mutableListOf<String>()
            for (something in channel) {
                if (some condition based on something) {

I don't think you need a channel here.
Since you consume the entire thing at once.
Perhaps a
instead of a channel.
Then you can do
val output = TODO("Call REST and make deferred list").awaitAll().filter { some condition based on something }
👍 1
Not sure if this will work - I have multiple REST calls all returning one item that I need to add to a collection once they have all finished - how would asynchronous jobs write to the deferred list ?
The jobs don't write to the list, the job scheduler does.
deferredList += async { }
as supposed to
async { deferredList += this }
👍 1
or use
filter{ }
it. You also can combine multiple calls using
-> https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-merge.html
👍 1
Thanks Domnic and Andrij - I'll try both.