What is the difference between Flow, StateFlow and SharedFlow?
-------------------------
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)
}
}
----------------------------
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.
val count = StateFlow(0)
fun main() = runBlocking {
launch {
count.collect { value ->
println("Count value: $value")
}
}
for (i in 1..5) {
count.value = i
}
}
----------------------------
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.
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)
}
}