Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: fire and forget async coroutines in Kotlin

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?

like image 231
Sherms Avatar asked Jun 27 '17 14:06

Sherms


2 Answers

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?

like image 100
Pau García Avatar answered Oct 22 '22 04:10

Pau García


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)
    }
}
like image 1
holi-java Avatar answered Oct 22 '22 02:10

holi-java