1. Why cleanup in coroutines is part of the contract
When you write sequential code, your brain really likes a simple picture: “first do A, then B, then C”. Coroutines do not break that picture (they actually create the illusion of a normal sequence), but real life adds a third variable: the code may end early, and it can end in different ways. And in coroutines this is not exotic — it is the basic reality: cancel(), an exception, an early return.
In structured concurrency this is especially important: if one part of an operation stops, the other parts may also stop (or must stop), and you do not want to leave “garbage” behind: a raised isLoading flag, a half-updated state, an “eternal spinner”, an unclosed resource, etc. Structured concurrency as a concept tells us: coroutines should be managed hierarchically and should complete predictably.
Let’s imagine the lifecycle of a single coroutine as a simple diagram:
stateDiagram-v2
[*] --> Running
Running --> Completed: successfully reached the end
Running --> Cancelled: cancel()
Running --> Failed: exception
Completed --> [*]
Cancelled --> [*]
Failed --> [*]
Today’s focus: learn to write code so that the last step, “put everything in order”, runs on any exit.
2. try/finally as a completion guarantee
finally in Kotlin: a quick reminder
Sometimes it helps to pretend for a minute that coroutines do not exist and recall the basic idea of try/finally. In Kotlin, a finally block is where you write actions that must be performed no matter what: whether an error happened or not, whether you left the try via return or reached the end.
One more important (and often forgotten) fact: in Kotlin, try must have either catch, or finally (or both). That is, a “plain try { ... }” does not exist — the compiler will not allow it.
A mini example without coroutines, just to refresh the intuition:
fun main() {
try {
println("Start") // Start
error("boom")
} finally {
println("Cleanup") // Cleanup
}
// println("End") // we will not reach here because of error(...)
}
And a small note about style: in Kotlin it is customary to write } finally { on the same line — this is part of the formatting conventions, and such code is noticeably easier to read.
Coroutine cancellation: why finally runs
When you first hear “coroutine cancellation”, it is easy to imagine a “Kill -9” button that instantly kills execution. But we already know: cancellation is a stop request, and the coroutine “agrees” to stop at the nearest suspension points (delay(), waiting, etc.) or when it checks isActive itself.
And here is the key point of the day: cancellation is also an exit from the coroutine. And if it is an exit, then finally is your guaranteed chance to “close the door and turn off the lights”.
Let’s look at a small example that demonstrates the idea as directly as possible:
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(10) { i ->
delay(50)
println("working $i") // working 0, working 1, ...
}
} finally {
println("cleanup runs anyway") // cleanup runs anyway
}
}
delay(130)
job.cancelAndJoin()
println("main finished") // main finished
}
Here we do an important thing: not just cancel(), but cancelAndJoin(). That is, we did not “ask it to stop and go drink coffee”, but asked and waited until the coroutine actually completed, which means it had time to execute finally.
3. Where to keep cleanup: inside the coroutine and by levels of responsibility
“Managed from the outside, cleaned up on the inside”: cancelAndJoin() + try/finally
When people first start writing coroutines, they often try to do cleanup “from the outside”: “if it was cancelled, then somewhere after cancel() I will set a flag, print a message…”. And this sometimes works while the scenario is very small. But as soon as the coroutine becomes a bit more complex, with multiple exit points, that approach turns into a game of “guess where the code ends”.
A sound discipline looks like this: from the outside we manage the lifecycle (cancelAndJoin(), join()), and inside the coroutine we guarantee cleanup via try/finally. Inside the coroutine is exactly where it is easiest to see what it “owns”: which flags, which temporary resources, which logic.
Let’s continue our hypothetical practical console project (let it be “BudgetBuddy”: expense tracking and report generation). We have application state, and one of the commands starts a “long report export”. The export can be cancelled (for example, the user changed their mind).
Let’s create the simplest state:
data class AppState(
var exportInProgress: Boolean = false
)
Now the function that starts the export returns a Job. Notice: a Job is not “the export result”, but rather a “handle for lifecycle control”. So it is logical to keep cleanup inside that Job.
import kotlinx.coroutines.*
fun startReportExport(scope: CoroutineScope, state: AppState): Job =
scope.launch {
state.exportInProgress = true
try {
repeat(5) { step ->
delay(80)
println("export step ${step + 1}/5") // export step 1/5 ...
}
println("export done") // export done
} finally {
state.exportInProgress = false
println("export cleanup: flag reset") // export cleanup: flag reset
}
}
Now from the outside (for example, in main()) we can cancel the export and be confident: the flag will always return to normal.
Cleanup in child coroutines: finally at each level
It is very tempting to write one “big” try/finally in the parent coroutine and think that is enough. But structured concurrency teaches us a good habit: each level should clean up what it owns.
The parent owns the “operation as a whole”, while a child may own local things: a temporary buffer, its own status, its own slice of computation. So it is normal (and often correct) for finally to exist in both the parent and the children: they clean up different things.
Example: the parent starts two export “workers” — one prepares the data, the second “packs” it (in reality it could be anything, but for now we simulate with delay()).
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
try {
launch {
try {
delay(60)
println("prepare done") // prepare done
} finally {
println("prepare cleanup") // prepare cleanup
}
}
launch {
try {
delay(90)
println("pack done") // pack done
} finally {
println("pack cleanup") // pack cleanup
}
}
} finally {
println("parent cleanup") // parent cleanup
}
}
parent.join()
}
The idea here is not about the “order of lines” (it can vary), but about cleanup being distributed by responsibility. The parent guarantees its part, the children guarantee theirs.
4. Cleanup on errors and what finally should contain
Cleanup on errors: try/finally does not heal, but it cleans
There is a subtle psychological trap: if finally “always runs”, then you do not need to fear errors. No — you can (and sometimes should) fear them; it is just that errors will no longer leave a mess behind.
It is important to understand the role: finally does not catch an exception. It simply runs reliably on exit — and then the exception will either be handled by catch, or it will “bubble up” past the scope boundary.
Let’s show this using our export example: on the third step we suddenly fail with an error, but cleanup still runs:
import kotlinx.coroutines.*
fun main() = runBlocking {
val state = AppState()
val job = launch {
state.exportInProgress = true
try {
repeat(5) { step ->
delay(50)
if (step == 2) error("disk is full (pretend)")
println("step ${step + 1}") // step 1, step 2
}
} finally {
state.exportInProgress = false
println("cleanup after error") // cleanup after error
}
}
try {
job.join()
} catch (e: Exception) {
println("caught in main: ${e.message}") // caught in main: disk is full (pretend)
}
println("flag = ${state.exportInProgress}") // flag = false
}
The point of this example is not where exactly to catch the error (we discussed that in the previous lecture), but the guarantee: even on failure, the state returns to a correct one.
What to put in finally, and what not to
finally is a very powerful thing, and that is exactly why it is easy to abuse. After a few successful examples, the temptation appears: “Oh, then I’ll do everything I didn’t manage to do in finally”. And that is how you get 80-line finally blocks, which can fail themselves, can hang themselves, and turn the code into a drama.
A practical rule for our current level: keep cleanup short, fast, and as reliable as possible. It should return flags to normal, print a clear completion message, close what must be closed, and avoid complex branching.
It is handy to keep a small table in mind:
| What is good to do in finally | Why it is good | What is risky to do in finally | Why it is risky |
|---|---|---|---|
| Reset a state flag (exportInProgress = false) | Fast, predictable | Write large business logic | It can fail and “overwrite” the original root cause |
| Print a final message/log | Helps debugging | Do many actions that can also throw exceptions | Then debugging turns into detective work |
| Release a “locally created” resource | We return the system to normal | Assume that “if it was cancelled, cleanup is not needed” | It is needed precisely because it was cancelled |
Separately, it is important to remember the basic meaning of finally: in Kotlin it is exactly for code that must run regardless of the outcome of the try.
And yes, in Kotlin it is customary to format try/finally compactly and readably — this also reduces the chance of mistakes, because the code is easier to visually verify.
5. Mini scenario: export, cancellation, and guaranteed cleanup
Now let’s assemble a small, complete scenario: start an export, let it work for a bit, then simulate “the user cancelled”, and make sure cleanup always runs. In a real CLI this could be command input, but to avoid bringing in command parsing today, we will just cancel on a timer.
import kotlinx.coroutines.*
data class AppState(var exportInProgress: Boolean = false)
fun startReportExport(scope: CoroutineScope, state: AppState): Job =
scope.launch {
state.exportInProgress = true
try {
repeat(10) { i ->
delay(40)
println("export tick $i") // export tick 0, 1, 2...
}
println("export finished normally") // (we won't reach this on cancellation)
} finally {
state.exportInProgress = false
println("export cleanup (always)") // export cleanup (always)
}
}
fun main() = runBlocking {
val state = AppState()
val exportJob = startReportExport(this, state)
delay(130)
println("cancel requested") // cancel requested
exportJob.cancelAndJoin()
println("flag = ${state.exportInProgress}") // flag = false
}
If you see that flag is always false, then you have defeated one of the most insidious classes of bugs: “the activity indicator is on forever” and “the app state did not return to normal after cancellation”.
6. Typical mistakes with cleanup in coroutines
Mistake #1: doing cleanup “from the outside” and forgetting other exit paths.
If you reset a flag or print “done” only after join() in the external code, you miss situations where the coroutine completed with an exception, was cancelled, or exited early due to return. As a result, the application state diverges from reality: the work already ended, but the UI/logic thinks it is still running.
Mistake #2: calling cancel() but not waiting for completion and expecting cleanup to have already run.
Cancellation is a request, not an instant shutdown. If it matters that cleanup definitely happened (and it almost always matters), you need to wait for coroutine completion via join() or use cancelAndJoin() right away. Otherwise, the coroutine may “clean up” a bit later, while your code already moves on.
Mistake #3: turning finally into “a second main program”.
When finally grows, it becomes a source of new errors. The worst situation is when cleanup fails with an exception and you lose the original cause that you started debugging for in the first place. finally should be boring, short, and reliable — that is its superpower.
Mistake #4: not separating responsibility between parent and children.
If the parent coroutine “owns” only the overall operation, while child coroutines create their own temporary resources or states, trying to clean everything in one place is inconvenient and easy to get wrong. It is much calmer when each level has its own small try/finally that cleans up exactly what it created.
Mistake #5: confusing “cancellation is not an error” with “cleanup is not needed on cancellation”.
Yes, cancellation is a normal scenario, not necessarily a problem. But precisely because cancellation is normal, cleanup should be just as normal and mandatory: reset flags, finish the “operation”, bring the state to a consistent form. Otherwise cancellation turns into a “half-broken app” that behaves strangely later.
GO TO FULL VERSION