Kotlin flows. If i do return someFlow.onCompletion { .. }.also { .. }, will the also…
- User
Kotlin flows. If i do return someFlow.onCompletion { .. }.also { .. }, will the also block run after the flow completes or as soon as it starts?
Assistant
In Kotlin, when you chain operations like
onCompletionandalsoon aFlow, the order of execution depends on whether the operation is intermediate (likeonCompletion) or terminal (likecollect).Your Code:
return someFlow .onCompletion { ... } .also { ... }Behavior:
-
also { ... }runs immediately- The
alsoblock is called as soon as the chain is constructed, not when the flow completes. - It operates on the
Flowobject itself, not on the emissions or completion of the flow. - This is because
alsois a scope function (not a flow operator) and executes eagerly.
- The
-
onCompletion { ... }runs when the flow completes- This is a Flow operator and only executes when the flow finishes (either successfully or due to an error).
- It does not trigger flow execution by itself—you need a terminal operator (like
collect) to start the flow.
Example:
fun getFlow(): Flow<Int> { return flowOf(1, 2, 3) .onCompletion { println("Flow completed!") } .also { println("also block runs during construction!") } } fun main() = runBlocking { val myFlow = getFlow() // Prints: "also block runs during construction!" myFlow.collect { println(it) } // Prints: 1, 2, 3, then "Flow completed!" }Output:
also block runs during construction! 1 2 3 Flow completed!Key Takeaways:
alsoruns immediately when the flow is being built (not when it's collected).onCompletionruns later, when the flow finishes (after terminal operators likecollect).- If you want to run code after the flow completes, use
onCompletion(notalso).
If You Want
alsoto Run After Completion:You’d need to move it inside
onCompletion:someFlow .onCompletion { println("Flow completed!") also { println("This runs after completion") } }Hope this clears it up! Let me know if you have further questions.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.