androidengineers.Book a session
โ† All interview questions
KotlinIntermediate4 min

What happens if we call .cancel() from a coroutine scope?

Answer

For a scope containing a Job, scope.cancel() cancels that job and its children. Cancellation is a request: a blocking operation or CPU loop that never checks cancellation can continue until it reaches a cooperative boundary.

The cancelled parent job cannot be restarted. A normal launch using it inherits cancellation and does not execute its body; calling launch itself does not generally throw a synchronous cancellation exception. Special coroutine start modes have different entry behavior, so be precise about the default case.

Example

Keep the screen owner alive when replacing one operation:

private var searchJob: Job? = null

fun search(query: String) {
    searchJob?.cancel()
    searchJob = viewModelScope.launch {
        repository.search(query)
    }
}

The repository call must cooperate with cancellation. If an old request cannot be cancelled, guard against its late result overwriting the new search. Do not cancel viewModelScope to cancel just one search.

Follow-up to practise

When is cancelAndJoin() useful? When the caller must wait for a job and its cleanup to finish before proceeding. It suspends rather than blocking a thread. If all current children should stop while the parent remains reusable, cancelChildren() is another option, but it affects unrelated child operations too.

Reference

Kotlin: Cancellation and timeouts

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising