Sobes.tech
Junior — Middle

How do the approaches MVI, MVP, and MVVM differ in application architecture?

sobes.tech AI

Answer from AI

MVP (Model-View-Presenter), MVVM (Model-View-ViewModel), and MVI (Model-View-Intent) are architectural patterns used to separate concerns in applications, especially in Android.

  • MVP: The View is responsible for display and delegates user actions to the Presenter. The Presenter contains the logic and interacts with the Model. The View and Presenter are directly linked, with the Presenter updating the View.

  • MVVM: The View binds to the ViewModel through a binding mechanism (e.g., LiveData in Android). The ViewModel contains logic and state, and does not know about the View directly. This simplifies testing and reduces coupling.

  • MVI: Based on a unidirectional data flow. The View sends Intents (intentions), which are processed by business logic, changing the State. The View subscribes to State changes and updates accordingly. This ensures predictability and purity of states.

An example of simplified differences:

// MVP
interface View { fun showData(data: String) }
class Presenter(val view: View) { fun load() { val data = "Hello"; view.showData(data) } }

// MVVM
class ViewModel : ViewModel() {
  val data = MutableLiveData<String>()
  fun load() { data.value = "Hello" }
}

// MVI
sealed class Intent { object Load : Intent() }
data class State(val data: String = "")

fun reducer(state: State, intent: Intent): State = when(intent) {
  is Intent.Load -> state.copy(data = "Hello")
}

Thus, MVP is more imperative, MVVM involves binding and reactivity, and MVI features a unidirectional data flow and state management.