0Pricing
Kotlin Academy · Lesson

Converting Cold Flow to Hot with shareIn and stateIn

Transform cold Flows into hot streams with sharing operators.

Cold vs Hot Flows

Cold flows restart for each collector; hot flows share one upstream subscription. Converting cold to hot avoids redundant work when multiple collectors subscribe.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun expensiveFlow() = flow {
    println("Starting upstream work")  // runs once if shared
    repeat(3) { delay(100); emit(it) }
}
fun main() = runBlocking {
    val cold = expensiveFlow()
    // Two collectors = two executions:
    launch { cold.collect { } }
    launch { cold.collect { } }
    delay(500)
    coroutineContext.cancelChildren()
}

shareIn Basics

flow.shareIn(scope, started, replay) converts a cold Flow to a SharedFlow, sharing one upstream subscription.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val cold = flow {
        println("Upstream started once")
        repeat(5) { delay(100); emit(it) }
    }
    val hot = cold.shareIn(this, SharingStarted.Eagerly, replay = 0)
    launch { hot.collect { println("A: $it") } }
    launch { hot.collect { println("B: $it") } }
    delay(600)
    coroutineContext.cancelChildren()
}

All lessons in this course

  1. StateFlow: Hot State Holder for UI
  2. SharedFlow: Event Buses and One-Shot Events
  3. Converting Cold Flow to Hot with shareIn and stateIn
  4. Testing StateFlow and SharedFlow with Turbine
← Back to Kotlin Academy