Hey guys, I’m making 4 separate DB calls sequentia...
# coroutines
v
Hey guys, I’m making 4 separate DB calls sequentially, getting the results from each and returning an AggregatedResult(call1, call2, call3, call4) object with the results to the client. I’m trying to figure out how I can parallelize the DB calls and return the AggregatedResult() object once all DB 4 calls complete. Any hints as to which coroutine function to use?
r
Wrap the calls with
async { }
and then
.await()
?
Copy code
AggregatedResult(call1.await(), call2.await(), call3.await(), call4.await())
👍 1
j
Copy code
val result = coroutineScope {
    val dbRes1 = async { call1() }
    val dbRes2 = async { call2() }
    ...
    AggregatedResult(
        dbRes1.await(),
        dbRes2.await(),
        ...
    )
}
👍 1
Note that it's important to call all the async before the first await, so don't
async { .. }.await()
👍 4
v
Thanks! Let me try it out
m
Out of curiosity, why do you need parallel calls? In my app I need to fetch from a few tables at one time. I have parallelized it with coroutines (one jdbc connection and one query per
async
) to make it quicker. But recently I have found out that it is probably better, and has similar total query time, to not use coroutines but a single connection, start all queries first and then cyclically fetches one record from each ResultSet. I have not yet adopted this method but you may try it out too.