I'm trying to learn the right way to use Kotlin coroutines to do some parallel API calls. I've been able to get the expected results/process, but am wondering if there is a "more correct" way to do so.
Here's my contrived example of what I'm trying to do. Use case is essentially an inbound web request, and that request in turn needing to make a couple of API calls. Digging around led me to using launch
or async
:
// using launch
var recordExists = false
var otherRecordExists = false
coroutineScope {
launch {
recordExists = someHttpService.doesRecordExist(123)
}
launch {
otherRecordExists = someHttpService.doesRecordExist(456)
}
}
if (!recordExists || !otherRecordExists) {...}
vs
// using async
var recordExists = false
var otherRecordExists = false
coroutineScope {
val recordDeferred = async { someHttpService.doesRecordExist(123) }
val otherRecordDeferred = async { someHttpService.doesRecordExist(456) }
recordExists = recordDeferred.await()
otherRecordExists = otherRecordDeferred.await()
}
if (!recordExists || !otherRecordExists) {...}
I landed on using launch
because it felt cleaner, but not sure if that was the most appropriate decision reasoning...
Is there a specific reason to use one over the other that I'm overlooking?