Skip to content

Using cancelAndJoin in Kotlin

Kotlin, Coroutines, Cancellation1 min read

In Kotlin, the cancelAndJoin function is used to cancel a running coroutine and wait for its completion. This function is part of the Job interface, which represents a cancellable piece of work that is being executed in a coroutine.

To use cancelAndJoin, you must first obtain a reference to the Job object representing the coroutine you want to cancel. This can be done by calling the launch function, which returns a Job object representing the newly created coroutine. For example:

1val job = launch {
2 // code for the coroutine goes here

Once you have a reference to the Job object, you can call the cancelAndJoin function to cancel the coroutine and wait for its completion. This function returns a CancellationException if the coroutine was cancelled, or null if the coroutine completed normally.

Here is an example of how to use cancelAndJoin:

1try {
2 job.cancelAndJoin()
3} catch (e: CancellationException) {
4 // the coroutine was cancelled

It is important to note that cancelAndJoin will only cancel the coroutine if it has not already completed. If the coroutine has already completed, cancelAndJoin will simply return null without cancelling the coroutine.

You can also specify a timeout when calling cancelAndJoin, in case the coroutine takes longer than expected to complete. If the timeout is reached before the coroutine completes, cancelAndJoin will throw a TimeoutCancellationException.

1try {
2 job.cancelAndJoin(1000L)
3} catch (e: TimeoutCancellationException) {
4 // the coroutine did not complete within the specified timeout

In summary, the cancelAndJoin function is a useful tool for cancelling and waiting for the completion of a coroutine in Kotlin. It is important to handle the possible exceptions that may be thrown when using this function, as well as to consider using a timeout to avoid waiting indefinitely for a coroutine to complete.