Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-v3-0324· DeepSeekHugging Face LMArena Human Preference 140K

Kotlin flows. If i do return someFlow.onCompletion { .. }.also { .. }, will the also…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. 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?

  2. DeepSeek Assistant

    In Kotlin, when you chain operations like onCompletion and also on a Flow, the order of execution depends on whether the operation is intermediate (like onCompletion) or terminal (like collect).

    Your Code:

    return someFlow
        .onCompletion { ... }
        .also { ... }
    

    Behavior:

    1. also { ... } runs immediately

      • The also block is called as soon as the chain is constructed, not when the flow completes.
      • It operates on the Flow object itself, not on the emissions or completion of the flow.
      • This is because also is a scope function (not a flow operator) and executes eagerly.
    2. 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:

    • also runs immediately when the flow is being built (not when it's collected).
    • onCompletion runs later, when the flow finishes (after terminal operators like collect).
    • If you want to run code after the flow completes, use onCompletion (not also).

    If You Want also to 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.