top of page

Cold Flow vs Hot Flow in Android





Cold Flow

A cold flow starts emitting values only when it is collected. The collection process starts from the beginning for each new collector. Cold flows are suitable for cases where developers want to perform a certain operation for each collector independently, and the flow starts from scratch for each new collector. Kotlin's "Flow" is a cold flow.



fun getColdFlow(): Flow<Int> = flow {
    emit(1)
    delay(1_000)
    emit(2)
    delay(1_000)
    emit(3)
}


val coldFlow = getColdFlow()

GlobalScope.launch {
    launch {
        Log.d("ColdFlow", "start collecting initially")
        coldFlow.collect {
            Log.d("ColdFlow", "1 -> $it ")
        }
    }

    delay(2_000)

    launch {
        Log.d("ColdFlow", "start collecting after 2s again")
        coldFlow.collect {
            Log.d("ColdFlow", "2 -> $it ")
        }
    }
}

Output

start collecting cold flow initially
[1, 2, 3]
start collecting cold flow after 2s again
[1, 2, 3]

Hot Flow

Hot flow does not depend on collector. It stats emitting values instantly. It keeps emitting values, and collectors can join in at any point to start receiving the values. Hot flows are useful when developers want to share the same flow among multiple collectors, and the flow is not restarted for each collector. "SharedFlow" and "StateFlow" are hot flow.



fun getHotFlow(): SharedFlow<Int> = MutableSharedFlow<Int>().apply {
    GlobalScope.launch {
        delay(1_000)
        emit(1)
        delay(1_000)
        emit(2)
        delay(1_000)
        emit(3)
    }
}


val hotFlow = getHotFlow()

GlobalScope.launch {
    launch {
        Log.d("HotFlow", "start collecting hot flow initially")
        hotFlow.collect {
            Log.d("HotFlow", "1 -> $it ")
        }
    }

    delay(2_000)

    launch {
        Log.d("HotFlow", "start collecting hot flow after 2s again")
        hotFlow.collect {
            Log.d("HotFlow", "2 -> $it ")
        }
    }
}

Output

start collecting hot flow initially
[1, 2, 3]
start collecting hot flow after 2s again
[2, 3]

In the provided code example, it becomes evident that the emission of cold flow data is contingent upon the collector, whereas the emission of hot flow data remains independent of the collector.

Comentários


bottom of page