AndroidのMVVM vs MVI:2026年に選ぶべきアーキテクチャとは?

AndroidにおけるMVVMとMVIの徹底比較。メリット・デメリット、ユースケース、そして2026年に適切なアーキテクチャを選択するための実践的ガイド。

AndroidにおけるMVVMとMVIアーキテクチャの比較

適切なアーキテクチャを選択することは、Androidアプリケーションの保守性・テスト性・スケーラビリティに直接影響する重要な決断です。2026年において、エコシステムを支配しているのは2つのパターンです。業界標準のMVVMと、Jetpack Composeとともに注目を集めているリアクティブアプローチのMVIです。

選択の重みを理解する

誤ったアーキテクチャの選択は高くつきます。技術的負債、再現困難なバグ、そして苦痛なリファクタリングを招きます。各アプローチの強みと弱みを理解することで、長期的な問題を大幅に軽減できます。

MVVMを理解する:確立された標準

MVVM(Model-View-ViewModel)は、JetpackのリリースからGoogleが推奨してきたアーキテクチャです。責務を3つの明確なレイヤーに分離し、コードを整理しやすく、テストしやすい構造にします。

MVVMの基本原則

MVVMパターンは明確な分離に基づいています。Modelはデータとビジネスロジックを管理し、ViewはUIを表示し、ViewModelはオブザーバブルなStateを公開することで両者を橋渡しします。

以下では、MVVMを使用してユーザープロフィール画面を実装します。この最初のサンプルは、オブザーバブルなStateとユーザー操作のためのメソッドを公開するViewModelの基本構造を示しています。

UserProfileViewModel.ktkotlin
// Classic MVVM ViewModel for a user profile screen
// It exposes observable state and methods for actions
class UserProfileViewModel(
    private val userRepository: UserRepository,
    private val analyticsTracker: AnalyticsTracker
) : ViewModel() {

    // Observable state with StateFlow - the View observes these changes
    private val _uiState = MutableStateFlow(UserProfileState())
    val uiState: StateFlow<UserProfileState> = _uiState.asStateFlow()

    // Separate loading state - MVVM allows multiple flows
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    // One-shot error messages
    private val _errorMessage = MutableSharedFlow<String>()
    val errorMessage: SharedFlow<String> = _errorMessage.asSharedFlow()

    // Initial profile loading
    fun loadProfile(userId: String) {
        viewModelScope.launch {
            _isLoading.value = true

            try {
                // Repository call to fetch data
                val user = userRepository.getUser(userId)

                // Update state with new data
                _uiState.update { currentState ->
                    currentState.copy(
                        user = user,
                        isEditing = false
                    )
                }

                // Analytics tracking
                analyticsTracker.trackProfileViewed(userId)

            } catch (e: Exception) {
                // Emit one-shot error message
                _errorMessage.emit("Unable to load profile")
            } finally {
                _isLoading.value = false
            }
        }
    }

    // Enable edit mode
    fun enableEditMode() {
        _uiState.update { it.copy(isEditing = true) }
    }

    // Save profile changes
    fun saveProfile(name: String, bio: String) {
        viewModelScope.launch {
            _isLoading.value = true

            try {
                val updatedUser = userRepository.updateUser(
                    _uiState.value.user?.id ?: return@launch,
                    name = name,
                    bio = bio
                )

                _uiState.update {
                    it.copy(user = updatedUser, isEditing = false)
                }

            } catch (e: Exception) {
                _errorMessage.emit("Failed to save profile")
            } finally {
                _isLoading.value = false
            }
        }
    }
}

// Data class representing the screen state
data class UserProfileState(
    val user: User? = null,
    val isEditing: Boolean = false
)

このViewModelは典型的なMVVMアプローチを示しています。複数のオブザーバブルFlow(メインState・ローディング・エラー)と、各ユーザーアクションに対応したパブリックメソッドが特徴です。

MVVMの利点

MVVMが広く採用されている理由となる強みがいくつかあります。

  • 親しみやすさ:ほとんどのAndroid開発者がこのパターンを知っています
  • 柔軟性:Stateの構造を自由に設計できます
  • エコシステム:Jetpack(LiveData、StateFlow、Hilt)との完璧な統合
  • シンプルさ:初心者にとって学習曲線が緩やかです

MVVMは、異なるスキルレベルの開発者が混在するチームに特に適しています。概念的なシンプルさが、オンボーディングを容易にします。

MVVMの限界

しかし、アプリケーションが成長するにつれてMVVMは限界を見せます。主な問題は、分散したState管理です。次の例はこのよくある問題を示しています。

ProblematicViewModel.ktkotlin
// Example MVVM ViewModel with fragmented state
// This pattern becomes problematic as the screen grows in complexity
class CheckoutViewModel : ViewModel() {

    // Problem: state scattered across multiple flows
    private val _cart = MutableStateFlow<List<CartItem>>(emptyList())
    private val _selectedAddress = MutableStateFlow<Address?>(null)
    private val _selectedPayment = MutableStateFlow<PaymentMethod?>(null)
    private val _promoCode = MutableStateFlow<String?>(null)
    private val _isLoading = MutableStateFlow(false)
    private val _error = MutableStateFlow<String?>(null)

    // Each modification can create temporary inconsistent states
    fun applyPromoCode(code: String) {
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null  // Reset error

            try {
                val discount = promoRepository.validate(code)
                _promoCode.value = code
                // Cart state also needs updating...
                // but there's a delay between the two updates
                recalculateCart()
            } catch (e: Exception) {
                _error.value = e.message
                _promoCode.value = null
            } finally {
                _isLoading.value = false
            }
        }
    }

    // Hard to guarantee consistency across all these states
    private fun recalculateCart() {
        // Complex logic depending on multiple states...
    }
}

この例は、MVVMでStateがどのように断片化し得るかを示しています。遷移の追跡やバグの再現が困難になります。

MVIを理解する:単方向アプローチ

MVI(Model-View-Intent)は異なる哲学を採用しています。単方向データフローと単一の不変Stateです。Reduxにインスパイアされたこのアプローチは、一貫性のないStateの問題を排除します。

MVIの基本原則

MVIでは、すべてが明確なサイクルに従います。ユーザーがIntent(アクション)を送信し、Reducerが現在のStateを新しいStateへと変換し、Viewがその単一のStateを表示します。予測可能で、テスト可能で、デバッグしやすい設計です。

以下では、同じプロフィール画面をMVIで実装します。Stateが一元化され、アクションが明示的に型付けされている点に注目してください。

UserProfileMviViewModel.ktkotlin
// MVI ViewModel for the same user profile screen
// Note the structure: Intent → Reducer → Single State
class UserProfileMviViewModel(
    private val userRepository: UserRepository,
    private val analyticsTracker: AnalyticsTracker
) : ViewModel() {

    // Single, immutable state - the absolute source of truth
    private val _state = MutableStateFlow(UserProfileState())
    val state: StateFlow<UserProfileState> = _state.asStateFlow()

    // Channel for side effects (navigation, snackbar)
    private val _sideEffect = Channel<UserProfileSideEffect>()
    val sideEffect: Flow<UserProfileSideEffect> = _sideEffect.receiveAsFlow()

    // Single entry point for all user actions
    fun onIntent(intent: UserProfileIntent) {
        when (intent) {
            is UserProfileIntent.LoadProfile -> loadProfile(intent.userId)
            is UserProfileIntent.EnableEditMode -> enableEditMode()
            is UserProfileIntent.SaveProfile -> saveProfile(intent.name, intent.bio)
            is UserProfileIntent.CancelEdit -> cancelEdit()
        }
    }

    private fun loadProfile(userId: String) {
        viewModelScope.launch {
            // Transition to loading state
            _state.update { it.copy(isLoading = true, error = null) }

            try {
                val user = userRepository.getUser(userId)

                // Single atomic state update
                _state.update {
                    it.copy(
                        user = user,
                        isLoading = false,
                        error = null
                    )
                }

                analyticsTracker.trackProfileViewed(userId)

            } catch (e: Exception) {
                // Error state is part of the main state
                _state.update {
                    it.copy(
                        isLoading = false,
                        error = "Unable to load profile"
                    )
                }
            }
        }
    }

    private fun enableEditMode() {
        // Simple, predictable update
        _state.update { it.copy(isEditing = true) }
    }

    private fun saveProfile(name: String, bio: String) {
        viewModelScope.launch {
            val currentUser = _state.value.user ?: return@launch

            _state.update { it.copy(isLoading = true) }

            try {
                val updatedUser = userRepository.updateUser(
                    currentUser.id,
                    name = name,
                    bio = bio
                )

                _state.update {
                    it.copy(
                        user = updatedUser,
                        isEditing = false,
                        isLoading = false
                    )
                }

                // Side effect to notify the user
                _sideEffect.send(UserProfileSideEffect.ShowSuccess("Profile updated"))

            } catch (e: Exception) {
                _state.update {
                    it.copy(isLoading = false, error = "Failed to save profile")
                }
            }
        }
    }

    private fun cancelEdit() {
        _state.update { it.copy(isEditing = false) }
    }
}

// All possible actions, explicitly typed
sealed class UserProfileIntent {
    data class LoadProfile(val userId: String) : UserProfileIntent()
    object EnableEditMode : UserProfileIntent()
    data class SaveProfile(val name: String, val bio: String) : UserProfileIntent()
    object CancelEdit : UserProfileIntent()
}

// Single, complete screen state
data class UserProfileState(
    val user: User? = null,
    val isLoading: Boolean = false,
    val isEditing: Boolean = false,
    val error: String? = null
)

// One-shot side effects
sealed class UserProfileSideEffect {
    data class ShowSuccess(val message: String) : UserProfileSideEffect()
    data class NavigateTo(val destination: String) : UserProfileSideEffect()
}

違いは明確です。単一のStateFlow、明示的なアクション、そして永続的なStateと一回限りのEffectの間のクリーンな分離です。

デバッグが容易になる

MVIでは、すべてのIntentとすべてのState遷移をログに記録できます。バグの再現が容易になります。Intentのシーケンスを再生するだけで済みます。

Jetpack ComposeとMVI

MVIはJetpack Composeと特に相性が良いです。どちらも同じ哲学、不変のStateと宣言的UIを共有しているからです。ViewModelをComposeの画面に接続する方法を示します。

UserProfileScreen.ktkotlin
// Compose screen consuming MVI state
// The connection between ViewModel and UI is elegant and reactive
@Composable
fun UserProfileScreen(
    viewModel: UserProfileMviViewModel = hiltViewModel(),
    onNavigateBack: () -> Unit
) {
    // Collect the single state
    val state by viewModel.state.collectAsStateWithLifecycle()

    // Handle side effects
    LaunchedEffect(Unit) {
        viewModel.sideEffect.collect { effect ->
            when (effect) {
                is UserProfileSideEffect.ShowSuccess -> {
                    // Show snackbar
                }
                is UserProfileSideEffect.NavigateTo -> {
                    // Navigate
                }
            }
        }
    }

    // Purely declarative UI based on state
    UserProfileContent(
        state = state,
        onIntent = viewModel::onIntent
    )
}

@Composable
private fun UserProfileContent(
    state: UserProfileState,
    onIntent: (UserProfileIntent) -> Unit
) {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {

        // Conditional rendering based on the single state
        when {
            state.isLoading -> {
                CircularProgressIndicator(
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
            }
            state.error != null -> {
                ErrorMessage(
                    message = state.error,
                    onRetry = {
                        state.user?.id?.let {
                            onIntent(UserProfileIntent.LoadProfile(it))
                        }
                    }
                )
            }
            state.user != null -> {
                ProfileCard(
                    user = state.user,
                    isEditing = state.isEditing,
                    onEditClick = { onIntent(UserProfileIntent.EnableEditMode) },
                    onSaveClick = { name, bio ->
                        onIntent(UserProfileIntent.SaveProfile(name, bio))
                    },
                    onCancelClick = { onIntent(UserProfileIntent.CancelEdit) }
                )
            }
        }
    }
}

UIはStateの純粋な関数となります。予測可能で、テスト可能で、隠れた副作用がありません。

詳細比較

両方のパターンを実際に確認した後、本番環境で真に重要な基準で比較します。

State管理

根本的な違いはState管理にあります。この差異は長期的な保守性に直接影響します。

StateComparison.ktkotlin
// MVVM: potentially fragmented state
class MvvmViewModel : ViewModel() {
    // Multiple sources of truth - manual synchronization needed
    private val _users = MutableStateFlow<List<User>>(emptyList())
    private val _selectedUser = MutableStateFlow<User?>(null)
    private val _isLoading = MutableStateFlow(false)
    private val _searchQuery = MutableStateFlow("")

    // What happens if _selectedUser points to a user
    // that's no longer in _users after a refresh?
    // → Inconsistent state that's hard to detect
}

// MVI: consistent state by construction
class MviViewModel : ViewModel() {
    // Single source of truth - inconsistencies are impossible
    private val _state = MutableStateFlow(UsersState())

    data class UsersState(
        val users: List<User> = emptyList(),
        val selectedUser: User? = null,  // Always consistent with users
        val isLoading: Boolean = false,
        val searchQuery: String = ""
    )

    // Each update automatically maintains invariants
    private fun selectUser(userId: String) {
        _state.update { currentState ->
            currentState.copy(
                selectedUser = currentState.users.find { it.id == userId }
            )
        }
    }
}
幽霊バグ

MVVMでは、一貫性のないStateが断続的なバグとして現れることが多く、再現が困難です。MVIでは、Stateが無効な場合、決定論的に無効となります。

アーキテクチャのテスト可能性

両アーキテクチャともテスト可能ですが、MVIはその予測可能性によって大きな優位性を持ちます。

TestComparison.ktkotlin
// MVVM test: requires verifying multiple flows
@Test
fun `loadUsers should update state correctly`() = runTest {
    val viewModel = MvvmViewModel(fakeRepository)

    // Observe multiple flows simultaneously
    val users = mutableListOf<List<User>>()
    val loadingStates = mutableListOf<Boolean>()

    val job1 = launch { viewModel.users.toList(users) }
    val job2 = launch { viewModel.isLoading.toList(loadingStates) }

    viewModel.loadUsers()
    advanceUntilIdle()

    // Assertions on different flows
    assertThat(users.last()).isEqualTo(expectedUsers)
    assertThat(loadingStates).containsExactly(false, true, false)

    job1.cancel()
    job2.cancel()
}

// MVI test: single flow to verify, clear state sequence
@Test
fun `LoadUsers intent should produce correct state sequence`() = runTest {
    val viewModel = MviViewModel(fakeRepository)

    // Collect all states in order
    val states = mutableListOf<UsersState>()
    val job = launch { viewModel.state.toList(states) }

    // Send the intent
    viewModel.onIntent(UsersIntent.LoadUsers)
    advanceUntilIdle()

    // Verify the exact state sequence
    assertThat(states).containsExactly(
        UsersState(),                                    // Initial
        UsersState(isLoading = true),                   // Loading
        UsersState(users = expectedUsers, isLoading = false)  // Success
    )

    job.cancel()
}

MVIはState遷移の正確なシーケンスをテストできるようにします。多くの操作を伴う複雑な画面に特に有用です。

複雑性とボイラープレート

トレードオフについて正直に述べます。MVIはより多くのボイラープレートコードと概念の深い理解を必要とします。

BoilerplateComparison.ktkotlin
// MVVM: quick start, less code
class SimpleViewModel : ViewModel() {
    private val _name = MutableStateFlow("")
    val name: StateFlow<String> = _name.asStateFlow()

    fun updateName(newName: String) {
        _name.value = newName
    }
}
// Total: ~10 lines

// MVI: more structure, more code
class SimpleMviViewModel : ViewModel() {
    private val _state = MutableStateFlow(SimpleState())
    val state: StateFlow<SimpleState> = _state.asStateFlow()

    fun onIntent(intent: SimpleIntent) {
        when (intent) {
            is SimpleIntent.UpdateName -> {
                _state.update { it.copy(name = intent.name) }
            }
        }
    }
}

data class SimpleState(val name: String = "")

sealed class SimpleIntent {
    data class UpdateName(val name: String) : SimpleIntent()
}
// Total: ~20 lines

シンプルな画面の場合、MVIは過剰に思えるかもしれません。しかしこの構造は、画面の複雑性が増すにつれて報われます。

Androidの面接対策はできていますか?

インタラクティブなシミュレーター、flashcards、技術テストで練習しましょう。

MVVMを選ぶべき時

MVVMはいくつかの状況において実用的な選択肢であり続けます。

既存のプロジェクト

アプリケーションがすでにMVVMを使用している場合、MVIへの移行はかなりの労力を伴います。既存のMVVM構造を改善するほうが賢明なことが多いです。

ジュニアまたは混合チーム

MVVMのほうが取り組みやすいです。初心者の開発者がいるチームは、MVIよりもMVVMでより早く生産性を発揮できます。

シンプルな画面

Stateや操作が少ない画面の場合、MVIは比例した利益なしに複雑性を増加させます。

SettingsViewModel.ktkotlin
// For a simple settings screen, MVVM is plenty
class SettingsViewModel(
    private val preferencesRepository: PreferencesRepository
) : ViewModel() {

    val darkMode = preferencesRepository.darkModeFlow
        .stateIn(viewModelScope, SharingStarted.Lazily, false)

    val notificationsEnabled = preferencesRepository.notificationsFlow
        .stateIn(viewModelScope, SharingStarted.Lazily, true)

    fun toggleDarkMode() {
        viewModelScope.launch {
            preferencesRepository.setDarkMode(!darkMode.value)
        }
    }

    fun toggleNotifications() {
        viewModelScope.launch {
            preferencesRepository.setNotifications(!notificationsEnabled.value)
        }
    }
}

MVIを選ぶべき時

MVIは特定のコンテキストでその価値を発揮します。

複雑なStateを持つアプリケーション

画面に多くの相互依存するStateがある場合、MVIは一貫性を保証します。

CheckoutState.ktkotlin
// Checkout screen with complex state: MVI excels
data class CheckoutState(
    val cartItems: List<CartItem> = emptyList(),
    val selectedAddress: Address? = null,
    val selectedPayment: PaymentMethod? = null,
    val promoCode: PromoCode? = null,
    val deliveryOptions: List<DeliveryOption> = emptyList(),
    val selectedDelivery: DeliveryOption? = null,
    val subtotal: Money = Money.ZERO,
    val discount: Money = Money.ZERO,
    val deliveryFee: Money = Money.ZERO,
    val total: Money = Money.ZERO,
    val isLoading: Boolean = false,
    val error: CheckoutError? = null,
    val step: CheckoutStep = CheckoutStep.CART
) {
    // Verifiable invariants
    init {
        require(total == subtotal - discount + deliveryFee) {
            "Total inconsistent with components"
        }
    }
}

sealed class CheckoutIntent {
    data class AddItem(val item: CartItem) : CheckoutIntent()
    data class RemoveItem(val itemId: String) : CheckoutIntent()
    data class SelectAddress(val address: Address) : CheckoutIntent()
    data class SelectPayment(val method: PaymentMethod) : CheckoutIntent()
    data class ApplyPromo(val code: String) : CheckoutIntent()
    object RemovePromo : CheckoutIntent()
    data class SelectDelivery(val option: DeliveryOption) : CheckoutIntent()
    object ProceedToPayment : CheckoutIntent()
    object ConfirmOrder : CheckoutIntent()
}

リアルタイムアプリケーション

WebSocket、プッシュ通知、またはリアルタイム同期を持つアプリでは、MVIが複数のデータストリームをエレガントに処理します。

厳格なデバッグ要件がある場面

規制された領域(フィンテック、ヘルスケア)では、イベントの正確なシーケンスを再現できる能力が非常に重要です。

MVIにより「タイムトラベルデバッグ」の実装が容易になります。すべてのStateを記録し、ユーザーのセッションを再生することができます。

ハイブリッドアプローチ:両方の長所を取る

実際には、多くのチームがハイブリッドアプローチを採用しています。複雑な画面にはMVI、シンプルな画面には簡略化されたMVVMを使用します。推奨パターンを示します。

MviViewModel.ktkotlin
// Base ViewModel with lightweight MVI structure
// Reusable for all screens
abstract class MviViewModel<S, I>(initialState: S) : ViewModel() {

    private val _state = MutableStateFlow(initialState)
    val state: StateFlow<S> = _state.asStateFlow()

    protected val currentState: S get() = _state.value

    // Single entry point for intents
    abstract fun onIntent(intent: I)

    // Helper to update state
    protected fun updateState(reducer: S.() -> S) {
        _state.update { it.reducer() }
    }
}

// Concrete implementation stays simple
class ProfileViewModel(
    private val userRepository: UserRepository
) : MviViewModel<ProfileState, ProfileIntent>(ProfileState()) {

    override fun onIntent(intent: ProfileIntent) {
        when (intent) {
            is ProfileIntent.Load -> load(intent.userId)
            is ProfileIntent.Refresh -> refresh()
            is ProfileIntent.ToggleFavorite -> toggleFavorite()
        }
    }

    private fun load(userId: String) {
        viewModelScope.launch {
            updateState { copy(isLoading = true) }

            val user = userRepository.getUser(userId)

            updateState {
                copy(user = user, isLoading = false)
            }
        }
    }

    private fun refresh() = load(currentState.user?.id ?: return)

    private fun toggleFavorite() {
        updateState {
            copy(user = user?.copy(isFavorite = !user.isFavorite))
        }
    }
}

このアプローチは、過剰なボイラープレートなしにMVIの利点(単一State、型付きIntent)を提供します。

2026年における推奨事項

コンテキストに応じた2つのアーキテクチャ間の選択についての推奨事項を示します。

ComposeによるNewプロジェクトの場合

最初からMVIを採用してください。ComposeとMVIは同じ哲学を共有しており、初期投資はすぐに回収されます。

既存のView based プロジェクトの場合

MVVMを維持しながら、MVIのベストプラクティスを段階的に導入してください。ViewModelの単一State、sealed classを使った型付きアクションです。

大規模チームの場合

一つのアプローチで標準化し、文書化してください。コードベースの一貫性は、パターンの選択そのものより重要です。

真の判断基準

最良のパターンは、チームが理解し正しく適用できるパターンです。よく実装されたMVVMは、理解が不十分なMVIより優れています。

まとめ

MVVMとMVIはどちらも、Androidアプリケーションのアーキテクチャとして有効なアプローチです。MVVMはシンプルさと親しみやすさを提供し、MVIは予測可能性とデバッグの容易さをもたらします。

判断チェックリスト

  • MVVMを選ぶ場合:ジュニアチーム、シンプルなプロジェクト、移行コストが高い
  • MVIを選ぶ場合:ネイティブCompose、複雑なState、デバッグ要件が厳しい
  • ハイブリッドアプローチを推奨:単一Stateの軽量MVI、過剰なエンジニアリングなし
  • 最優先事項:コードベース全体の一貫性

今すぐ練習を始めましょう!

面接シミュレーターと技術テストで知識をテストしましょう。

どちらを選択するにせよ、鍵となるのは各アプローチの強みと弱みを理解して、情報に基づいた判断を下すことです。最良のコードとは、チームが長期にわたって安心してメンテナンスできるコードです。

タグ

#android
#mvvm
#mvi
#architecture
#jetpack compose

共有

関連記事