MutableStateFlow
and MutableSharedFlow
are very convenient for storing and adding updates of some data structures in
event-driven paradigm. This is widely used in Android Views for handling updates. While it’s extremely useful to manage such objects inside some
class, it’s not recommended to expose them outside of the class.
When properties of the types MutableStateFlow
or MutableSharedFlow
are accessible from outside of a class, data updates
cannot be verified properly anymore. It is generally recommended to have only one class responsible for updating these flows, otherwise inconsistency
issues and problems with maintainability, as well as increased error-proneness may be introduced.
To restrict write access, StateFlow
or SharedFlow
should be used together with private MutableStateFlow
or
MutableSharedFlow
fields.
This rule raises an issue when encountering a public or internal property of the type MutableStateFlow
or
MutableSharedFlow
.
Noncompliant code example
class MyView : ViewModel() {
val state = MutableStateFlow(State.New)
}
Compliant solution
class MyView : ViewModel() {
private val _state = MutableStateFlow(State.New)
val state: StateFlow<LatestNewsUiState> = _uiState
}