I'm trying to run x number of async operations and...
# coroutines
d
I'm trying to run x number of async operations and then combine the results when the async operations are all done. Kinda like Promises.all
Here's a convoluted example but it should get the point across:
o
there's an extension function for
List<Deferred<T>>
,
awaitAll(): List<T>
d
Awesome, thanks!
My followup question, is this the "best" way of doing this? Or is another technique more idiomatic?
o
if you specifically want them to be async, then this is probably the simplest way
depending on how complicated it gets,
Flow
may be useful, but it doesn't yet have good concurrency primitives, it's best for serial processing. You can emulate concurrent processing by using
.map { async { } }
and
.buffered
, but it's certainly more complex than this
d
What if
getInt
contains a blocking call? Like an http library that doesn't support coroutines?
o
you should wrap it with a
suspend
function +
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
, e.g.:
Copy code
suspend fun suspendGetInt(i: Int) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { getInt(i) }
if you have e.g. callbacks, other async tools, there are more efficient ways to wrap those as well
but if the only option is to block, this is the solution
d
We're kinda stuck with what Swagger generates for us. Still looking for a swagger code-gen that supports coroutines.
What if we have a callback (or even a Promise)?
d
Thank you!
o
I think you can do something similar with a Promise (
.then
is basically a callback)
👍 1