Sobes.tech
Junior — Middle

How can you implement data list loading in an MVI architecture?

sobes.tech AI

Answer from AI

In MVI (Model-View-Intent) architecture, loading a data list is usually implemented through the following steps:

  1. Intent — a user action or event, such as a request to load a list.
  2. Model — processing the intent, for example, calling a repository or use case that loads data (from network or database).
  3. ViewState — forming the view state, which contains the loaded list and loading status (loading, success, error).
  4. View — subscribes to changes in ViewState and displays the list or a loading indicator.

Example in Kotlin using Flow:

sealed class Intent {
    object LoadList : Intent()
}

data class ViewState(
    val isLoading: Boolean = false,
    val items: List<String> = emptyList(),
    val error: String? = null
)

class ViewModel {
    private val _state = MutableStateFlow(ViewState())
    val state: StateFlow<ViewState> = _state

    fun processIntent(intent: Intent) {
        when (intent) {
            is Intent.LoadList -> loadData()
        }
    }

    private fun loadData() {
        _state.value = _state.value.copy(isLoading = true, error = null)
        // Simulate loading
        viewModelScope.launch {
            try {
                val data = repository.getList() // suspend function
                _state.value = ViewState(isLoading = false, items = data)
            } catch (e: Exception) {
                _state.value = ViewState(isLoading = false, error = e.message)
            }
        }
    }
}

Thus, list loading occurs through intent processing, state updating, and reactive UI updates.