Kotlin Coroutines StateFlow sample Android application
Sample Android application that show how can we use Kotlin Coroutines StateFlow
.
StateFlow
is a new class introduced in version 1.3.6 of the Kotlin Coroutines library which works in the following way:
Flow
with a single updatable data value that emits updates to the value to its collectors.ConflatedBroadcastChannel
in the future.
For example, the following class represents an integer state that increments its value by calling the method incrementCount
:
class CountModel {
private val _countState = MutableStateFlow(0) // Private mutable state flow
val countState: StateFlow<Int> get() = _countState // Public read-only state flow
fun incrementCount() {
_countState.value++
}
}
Now in a possible activity we can observe countState
to keep track of its updates:
lifecycleScope.launch {
countModel.countState.collect { value ->
countTextView.text = "$value"
}
}
This collector will be executed whenever the value of countState
is updated. Also it’s lifecycle-aware as we’ve used it under lifecycleScope
.