I read some kotlin project samples code, I find many author like to Code A.
I think Code B is more simpler.
1: Is Code B good way?
2: Can I always use private set intead of private val in Android Studio?
Code A
private val _uiState = MutableStateFlow(InterestsUiState(loading = true))
val uiState: StateFlow<InterestsUiState> = _uiState.asStateFlow()
Code B
var uiState = MutableStateFlow(InterestsUiState(loading = true))
private set
CodePudding user response:
A, B are not the same code.
In code A, define another variable as StateFlow
is preventing to change value in StateFlow
from out of class.
In code B, you can update value in StateFlow
from out of class.
Because you can refer MutableStateFlow
.
Mutating state variable itself and Mutating state in StateFlow
is different.
Observer observing StateFlow
is received event when value in StateFlow
is change but change StateFlow
itself.
In other word, you should use code A for prevent to unexpected mutating from outer