I've been reading up on Kotlin co-routines but am not finding the answer to a specific problem.
Say I want to iterate over a collection making an API call for each element (in this particular case pushing a file to Amazon S3). I want these calls to be handled by an async coroutine so as not to block the underlying thread while waiting.
I do not need a return value from the request, only to log exceptions.
How would I create a "fire and forget" async coroutine to make one of these requests?
Notice that, if no specific coroutine scope exists already (not a suspend function, i.e.) you can use:
fun Process (item: String): Response {
GlobalScope.launch {
... <YOUR ASYNC (Processing) CODE GOES HERE> ...
}
... <YOUR SYNC CODE GOES HERE> ...
return Response("Your request for $item is being processed...")
}
This way you can return a quick answer (acting as an Acknowledge) stating that it has been received and you are processing it, without blocking the client/consumer, in a Fire&Forget fashion.
But be careful with posible memory leaks when the async part raises exceptions, for instance. Extending CoroutineScope is a better approach. More info at https://discuss.kotlinlang.org/t/unavoidable-memory-leak-when-using-coroutines/11603/7 and Why not use GlobalScope.launch?
maybe kotlinx.coroutines#launch or kotlinx.coroutines#async meet your needs. for examples:
launch(CommonPool) {
for(item in collection){
val result = apiCall(item);
log(result);
}
}
OR
for(item in collection){
launch(CommonPool) {
val result = apiCall(item)
log(result)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With