How can I use Coroutines.invokeOnCompletion

I’ve the below code that is working fine:

scope.launch {
      val detectedFaces = FaceDetection.detectFaces(bitmap)
      println("Detected Faces = $detectedFaces")
}

I tried to re-write it using invokeOnCompletion but the returned value was null which means I wrongly use it?

val detectedFaces = scope.launch { FaceDetection.detectFaces(bitmap) }
detectedFaces.invokeOnCompletion {
    println("Detected Faces = $detectedFaces")
}

The value passed to the handler represents the exception that caused the coroutine to fail, see the docs:

typealias CompletionHandler = (cause: Throwable?) -> Unit

Additionally, Jobs themselves do not have any type of “result”. In general, this callback is intended for error handling or used internally. There is no reason to use code in the style of your second snippet as this resembles Future-style CPS and goes against Kotlin’s coroutine design principles.

1 Like

My suggestion would be:
val detectedFaces: String? = null
scope.launch {
detectedFaces = FaceDetection.detectFaces(bitmap)
}.invokeOnCompletion {
println(“Detected Faces = $detectedFaces”)
}