Sobes.tech
Junior — Middle

Can you describe the main cold flows in Coroutines and their features?

sobes.tech AI

Answer from AI

Cold flows in Kotlin Coroutines are streams that start emitting data only when they are subscribed to (collect). Until then, they do not perform any computations or consume resources.

Features of cold flows:

  • Lazy execution: the code inside the flow runs only upon subscription.
  • Multiple subscriptions lead to re-execution of the code.
  • They allow describing data sequences that are generated on demand.

Example of a cold flow:

val flow = flow {
    println("Flow started")
    emit(1)
    emit(2)
}

fun main() = runBlocking {
    println("Before collect")
    flow.collect { value -> println(value) }
    println("After collect")
}

The output will be:

Before collect
Flow started
1
2
After collect

This shows that the code inside the flow runs only when collect is called.