I have the following use case: I fire off a numbe...
# coroutines
p
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) {
                    output.add(something)
                }

            }
d
I don't think you need a channel here.
Since you consume the entire thing at once.
Perhaps a
List<Deferred<String>>
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
p
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 ?
d
The jobs don't write to the list, the job scheduler does.
deferredList += async { }
as supposed to
async { deferredList += this }
.
👍 1
a
or use
Flow<String>
and
filter{ }
it. You also can combine multiple calls using
flatMapMerge
-> https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-merge.html
👍 1
p
Thanks Domnic and Andrij - I'll try both.