Say I want to run 2 api calls in parallel, then ma...
# coroutines
u
Say I want to run 2 api calls in parallel, then map their results together, and then save that to db. Question is, should I try to scope down the "
coroutineScope { .. }
length, or is it okay to have ot extend to the full function body? Whats more idiomatic?
j
In general I'd say make it as local as possible. It makes it easier to find concurrency whereas if it's scoped to the whole function you need to search through everything
1
u
but that means to return tuple right? then to destructure etc.. wont that make it harder to read?
j
I think you can still do the combine together part within and return the single thing for db insert
u
oh yea, neat..thanks!
k
Furthermore, you don't have to use tuples to return stuff out of scope, you just delay the initialization of the values because
coroutineScope
has the
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
contract. So you can say:
Copy code
val x: Int
val y: Int

coroutineScope {
    x = 1
    y = 2
}

println("x: $x, y: $y")
Sure, that's somewhat annoying, but still often cleaner than the alternatives.
today i learned 3