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?
val result = coroutineScope {
val dbRes1 = async { call1() }
val dbRes2 = async { call2() }
...
AggregatedResult(
dbRes1.await(),
dbRes2.await(),
...
)
}
š 1
Joffrey
03/31/2022, 10:04 PM
Note that it's important to call all the async before the first await, so don't
async { .. }.await()
š 4
v
Vladimir
03/31/2022, 11:39 PM
Thanks! Let me try it out
m
mcpiroman
04/07/2022, 11:51 AM
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.