跪拜 Guibai
← All articles
Architecture · Android · Kotlin

Android Architecture's Four Ages: From MVC to MVI, with the Same App in Kotlin

By 碳基Agent ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

The four-pattern walkthrough shows exactly which architectural costs you trade for which benefits, so a team can stop cargo-culting MVI and pick the pattern that matches its bug count, UI framework, and tolerance for boilerplate. The pragmatic hybrid Google now endorses (single StateFlow output, direct method calls input) gives most projects MVI-grade state safety without forcing sealed Intent classes on every trivial form.

Summary

Android client architecture has gone through four major generations: MVC, MVP, MVVM, and MVI. Rather than memorizing what each letter stands for, the useful question is why each previous architecture died and what nerve the next one changed. This article answers that by implementing the same business scenario (load a user, like to level up, rotate the screen, fail a request) in all four patterns, with Kotlin code and a companion GitHub project that runs all six implementations (four plus two pragmatic variants).

The evolution tracks three escalating goals: responsibility decoupling (MVC to MVP), reactive data-driven UI (MVP to MVVM), and unidirectional data flow with state convergence (MVVM to MVI). MVC collapses because Activity becomes a God class that mixes view, controller, and business logic, leaks memory on rotation, and is untestable. MVP extracts business logic into a presenter but pays with interface explosion (contract hell) and imperative UI calls that easily miss state resets. MVVM removes the contracts using LiveData/StateFlow, but scatters state across many independent streams, producing "ghost states" where UI elements contradict each other, and LiveData's sticky events replay one-time toasts after rotation.

MVI solves those three by using a single immutable UiState, a single dispatch(Intent) entry, and a Channel-based UiEffect for one-time events. It works with both Jetpack Compose and traditional XML via state slicing (map + distinctUntilChanged). The article closes with pragmatic selection advice: merge scattered LiveData into one StateFlow for legacy MVVM, adopt a "converged output, direct-call input" hybrid for normal development (the official Now in Android approach), and reserve full MVI for new Compose projects or high-interaction pages. A runnable ArchEvolutionDemo repo accompanies every example.

Takeaways
— MVC in Android turns Activity into a God class that mixes view, controller, and business logic, causing memory leaks on rotation, near-zero unit testability, and states that vanish on config changes.
— MVP extracts logic into a pure Kotlin Presenter with a Contract.View interface, enabling fast JVM unit tests, but explodes interface surface (one method per trivial UI change) and still drops data on rotation because the Presenter is recreated.
— MVVM using Jetpack ViewModel and LiveData survives rotation automatically, eliminating contract interfaces, but scatters state across 15-30 separate MutableLiveData instances, making ghost states (e.g., data shown while error banner still visible) common when async results interleave.
— LiveData's sticky behavior replays the last value to new observers, so a one-time Toast fired before rotation reappears after rotation unless wrapped in an Event class.
— MVI converges all UI state into a single immutable data class UiState, exposes one StateFlow, accepts only one dispatch(Intent) entry, and separates one-time side effects (Toast, navigation) into a Channel-based UiEffect that is consumed once and never replayed.
— In MVI, using MutableStateFlow.update or getAndUpdate requires the lambda to be pure (no side effects or logging inside), because CAS retries re-execute the lambda on contention.
— MVI works with XML views by slicing the UiState with map + distinctUntilChanged to update only the controls affected by each field, avoiding expensive full-screen redraws.
— The article's pragmatic recommended pattern is 'converged output, direct-call input': keep a single StateFlow<UiState> as the only state output, but allow View code to call viewModel.loadUser() etc. directly instead of always defining a sealed Intent class and dispatch() method.
— Google's Now in Android encourages the pragmatic UDF pattern; full MVI with sealed Intent is best reserved for new Compose projects or complex interactive pages like chat sessions, cloud gaming consoles, or multi-step checkout.
— The companion project ArchEvolutionDemo implements the same business scenario six times (MVC, MVP, MVVM, MVI Compose, MVI XML, pragmatic) with a screen-level state log panel to compare data flows side by side.
Conclusions

The real driver of each architecture change is a specific, reproducible failure mode: a God Activity, a contract explosion, a ghost state, a sticky toast. Naming the failure mode makes the next architecture feel like a patch rather than a fashion.

Sticky event replay is fundamentally a semantics defect: mixing persistent state with one-time events in the same channel. MVI's separation of UiState and UiEffect is the clean fix, but the Channel-based UiEffect itself has a catch: it is point-to-point and buffers while backgrounded, so it trades replay for delayed delivery.

The pragmatic hybrid pattern (single StateFlow output, direct method calls input) suggests that once you have a single source of truth, the ceremony of a sealed Intent interface adds little for simple screens. It becomes valuable only when you need uniform interception, logging, or debouncing of user actions.

The article's honest admission that a flat data class UiState still permits illegal combinations (isLoading=true and isError=true) shows that compile-time state validation requires sealed interfaces; the choice between data class and sealed interface is a real engineering trade-off, not a stylistic one.

XML users of MVI must do manual state slicing with distinctUntilChanged, which reveals that MVI's convenience in Compose relies on smart recomposition. Without it, the pattern demands extra care to avoid needless layout passes.

Concepts & terms
God Activity (上帝类)
A term for Android Activity/Fragment classes that absorb too many responsibilities (lifecycle, view binding, network calls, business logic, data parsing), growing to thousands of lines and becoming hard to maintain or test.
Contract Hell (接口爆炸)
A side effect of MVP where every trivial UI action (hiding an error bar, showing a toast, logging) requires a new method in the Contract.View interface, which the Activity must implement and the Presenter must call, leading to interfaces with dozens or even fifty-plus methods.
Ghost State (幽灵状态)
An inconsistent UI state that arises when independent state variables fall out of synchronization, such as showing loaded data while an error banner is still visible because one flag was not reset after a previous failure.
Sticky Event (粘性事件)
A behavior of LiveData where a newly added observer immediately receives the last emitted value. For one-time events (like an error toast), this causes the event to be replayed after screen rotation, annoying users and leaking false side effects.
Unidirectional Data Flow (UDF, 单向数据流)
An architectural principle where UI events flow in one direction (Intent -> ViewModel -> State -> View). It makes state changes predictable and traceable, contrasting with the multi-entry, two-way bindings of MVVM.
UiState
In MVI, a single immutable data class that captures the complete UI state of a screen at a point in time. The View renders purely from it (UI = f(State)), and any change produces a new UiState via copy().
UiEffect
In MVI, a separate channel (typically a Kotlin Channel) for one-time side effects such as showing a Toast or navigating. It is consumed once and never replayed, unlike persistent UiState.
State Slicing (状态切片)
A technique used when applying MVI to XML views: using flow operators like map and distinctUntilChanged to collect only the subset of UiState fields needed by a particular view, avoiding whole-screen redraws on every state change.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗