Kotlin coroutines - Kick off function in api call and return api call without waiting

820 views Asked by At

I have an api call that I want to kick off a long running job and then return a 200 ok. Currently it will kick of the job and move on, but once the initial function finishes what it needs to do, it still seems to wait until the coroutine has finished. I'm sure this is related to my relatively new understanding of kotlin coroutines.

fun apiCall() {
   log.info("started")
   longJob()
   log.info("finished")
   
   return ResponseEntity.ok()
}

fun longJob() {
   runBlocking{
      launch {
        do stufff...
      }
   }
}

So basically I'm expected to see the logs print and then kick off the longJob and then see 200 in postman. But I'm actually getting both logs printed out as well as the job kicked off, but I don't see my 200ok until the job finishes.

1

There are 1 answers

1
Sergio On BEST ANSWER

If I understand correctly, you want to launch the longJob in background, and return 200ok status without waiting for longJob to finish. If this is the case then you can't use runBlocking here, it blocks the current thread until all jobs, launched in it, finish. You can create a CoroutineScope and launch and forget a long running task. The sample code:

val scope = CoroutineScope(Dispatchers.IO) // or CoroutineScope(Dispatchers.IO + SupervisorJob())

fun apiCall() {
   log.info("started")
   scope.launch { longJob() }
   log.info("finished")
   
   return ResponseEntity.ok()
}

In this sample logs "started" and "finished" will be printed before longJob() starts executing.