Search⌘ K
AI Features

Extension of SharedFlow

Explore how StateFlow serves as an extension of SharedFlow in Kotlin coroutines by always storing a single value. Understand the differences between MutableStateFlow and SharedFlow, its use as a modern LiveData alternative in Android, and observe how stateIn converts flows into StateFlow for state management in ViewModels.

We'll cover the following...

StateFlow

The StateFlow is an extension of the SharedFlow concept. It works similarly to SharedFlow when we set the replay parameter to 1. It always stores one value, which can be accessed using the value property.

Kotlin 1.5
interface StateFlow<out T> : SharedFlow<T> {
val value: T
}
interface MutableStateFlow<T> :
StateFlow<T>, MutableSharedFlow<T> {
override var value: T
fun compareAndSet(expect: T, update: T): Boolean
}

Note: Please note how the value property is overridden inside MutableStateFlow. In Kotlin, an open val property can be overridden with a var property. A val only ...