37 lines
1.4 KiB
Plaintext
37 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
`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
|
|
|
|
[source,kotlin]
|
|
----
|
|
class MyView : ViewModel() {
|
|
|
|
val state = MutableStateFlow(State.New)
|
|
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,kotlin]
|
|
----
|
|
class MyView : ViewModel() {
|
|
|
|
private val _state = MutableStateFlow(State.New)
|
|
val state: StateFlow<LatestNewsUiState> = _uiState
|
|
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://developer.android.com/kotlin/coroutines/coroutines-best-practices#mutable-types[Android Coroutines Best Practices]
|