Junior — Middle
How can you update the value of the State property in the MVI architecture?
sobes.tech AI
Answer from AI
In the MVI (Model-View-Intent) architecture, the state is usually an immutable object. To update the value of a State property, a new state object is created with the modified data, and then this new object is passed into a data stream (for example, via LiveData, StateFlow, or RxJava), which is subscribed to UI updates.
Example in Kotlin using data class and StateFlow:
// State definition
data class ViewState(val isLoading: Boolean, val data: List<String>)
// In ViewModel
private val _state = MutableStateFlow(ViewState(isLoading = false, data = emptyList()))
val state: StateFlow<ViewState> = _state
fun loadData() {
_state.value = _state.value.copy(isLoading = true)
// after data is loaded
_state.value = _state.value.copy(isLoading = false, data = listOf("item1", "item2"))
}
Thus, updates occur through creating a new instance of the state using the copy method, which ensures immutability and predictability of the state.