Great question! Let's break down what happens when you write:
return someFlow.onCompletion { /* completion handler */ }
.also { /* side effect block */ }
Understanding .also with Flows
The .also {} operator in Kotlin is a terminal operator, meaning it collects the flow and runs the lambda once per collection start — not once per item. It runs its lambda after the flow starts being collected, but before any items are emitted by the flow.
So, in this example:
return someFlow
.onCompletion { println("Completed") }
.also { println("Also block") }
Here’s what happens during collection (e.g., when someone calls launch { flow.collect() }):
- When the flow starts being collected:
- The code inside
.also { ... } runs immediately after collection begins, before any values are emitted.
- Then the actual flow emits items.
- Finally,
.onCompletion { ... } runs when the flow completes, whether normally or with an exception.
Summary of Execution Order
Assuming someFlow emits 1, 2, 3:
val flow = flow {
listOf(1, 2, 3).forEach {
emit(it)
}
}.onCompletion { println("onCompletion") }
.also { println("also block") }
// Somewhere else:
flow.launchAndCollectIn(scope)
Output order:
also block
1
2
3
onCompletion
Key Takeaways
.also {} runs as soon as the flow starts being collected, not after it completes.
.onCompletion {} runs when the flow finishes emitting items (successfully or with error).
- If you want to run something after the flow completes, use
.onCompletion {} or .launchAndCollectIn {} with a coroutine scope where you can continue after collection.
Let me know if you want to see how to make sure a block runs only after the flow completes processing all items!