In Kotlin Coroutines...
What is the difference between Flow, StateFlow and SharedFlow?
2023-01-31 17:33:15 - Mohamad Abuzaid
-------------------------
[1] Flow
Flow is a cold asynchronous stream of values that can be collected by a collector. Flow is similar to the concept of an Iterator in synchronous programming.
Cold Stream: which means that it will start emitting values only when a collector starts collecting them. Once a collector stops collecting, the flow stops emitting values.
fun intFlow(): Flow<Int> = flow {
for (i in 1..5) {
emit(i)
}
}
fun main() {
intFlow().collect {
println(it)
}
}
----------------------------
[2] StateFlow
A special kind of flow in Kotlin Coroutines that represents a state that can be observed and updated by multiple collectors.
Hot Stream: which means that it will start emitting values as soon as it is created and it will continue to emit new values even when there are no collectors.
- When a new collector is added later on: State Flow will emit the current value and it will emit new values every time the value changes.
val count = StateFlow(0)
fun main() = runBlocking {
launch {
count.collect { value ->
println("Count value: $value")
}
}
for (i in 1..5) {
count.value = i
}
}
----------------------------
[3] SharedFlow
Allows multiple collectors to share a single source of values, similar to a broadcast channel.
Hot Stream: which means that it will start emitting values as soon as it is created and it will continue to emit new values even when there are no collectors.
- Unlike "State Flow", "𝐒𝐡𝐚𝐫𝐞𝐝 𝐅𝐥𝐨𝐰" emits values only once and it uses a buffer to store the values. So if a new collector is added later on, it will not get the current value. Instead, it will have to read the previous values from the buffer.
val sharedFlow = SharedFlow<Int>(extraBufferCapacity = 100)
fun main() = runBlocking {
launch {
sharedFlow
.buffer()
.collect { value ->
println("Collected value: $value")
}
}
for (i in 1..5) {
sharedFlow.emit(i)
}
}