MVVM in practice

Learn MVVM in Android with Kotlin to master StateFlow, atomic UI state updates, lifecycle-aware collection, and the MVVM vs MVI architectural trade-off. About 25 minutes.

Why it matters

  • Stale or lost UI state after rotation is a common source of visible UI defects in production Android apps.
  • Interviewers probe StateFlow vs LiveData, the atomic update pattern, and lifecycle-aware collection; getting these wrong signals a mid-level gap.
  • Choosing MVVM over MVI (or vice versa) affects testability and team velocity; you must justify the choice, not just name it.
  • Collecting a flow in the wrong scope keeps updating a destroyed view or leaks it, and it is hard to reproduce in QA.

The simple explanation

  • Think of a restaurant kitchen (ViewModel) and a dining table (UI).
  • The kitchen holds one order ticket (UiState) that shows the current status.
  • The waiter brings new requests UP to the kitchen (events as function calls).
  • The kitchen rewrites the ticket and the table sees the new status DOWN (StateFlow emission).
  • The ticket is replaced, never edited in place (immutable data class).
  • If the table is cleared (view destroyed), the kitchen keeps the ticket (ViewModel survives rotation).

In MVVM the ViewModel owns a single StateFlow<UiState> that the UI collects. State flows down; user actions flow up as function calls on the ViewModel. UiState is an immutable data class (or sealed interface) with fields like isLoading, items, error.

The ViewModel wraps a MutableStateFlow privately and exposes a read-only StateFlow via asStateFlow(). Every write goes through the update { } extension, which makes the read-modify-write atomic: it reads the current value, applies the lambda and writes with compareAndSet, retrying if another coroutine changed the value in between. Using _state.value = ... is not atomic and can lose a concurrent update.

On the UI side, Compose uses collectAsStateWithLifecycle() from lifecycle-runtime-compose. In a Fragment you wrap collection in repeatOnLifecycle(Lifecycle.State.STARTED) inside viewLifecycleOwner.lifecycleScope. Collecting in the Fragment's own lifecycleScope keeps running after onDestroyView, so it can touch a destroyed view binding (a crash or a leak) and keeps working in the background.

For a derived or long-running cold flow, stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial) converts it to a hot StateFlow. The 5-second grace period prevents upstream restarts when the UI briefly loses and regains a collector during a configuration change.

ChoiceFlat data classSealed interface
Updatecopy() is trivialMust rebuild the variant
UI renderingCheck booleans / nullsExhaustive when
Best forIndependent fields that can change separatelyMutually exclusive modes (Loading, Content, Error)

MVVM uses state plus ViewModel methods. MVI adds a sealed intent type and a pure reducer that maps (state, intent) to the next state. MVI costs more boilerplate but gives one testable transition function and a single place to log every intent. Many teams find MVVM enough for simple CRUD screens and use MVI where many inputs change the same state; this is a team choice, not a rule.

Notes

  • MutableStateFlow stays private; expose StateFlow via asStateFlow(). Any public MutableStateFlow lets callers bypass ViewModel logic.
  • Use update { it.copy(...) } for every write. It is atomic. _state.value = ... is a plain set and can lose a concurrent update.
  • UiState is a data class with val fields and read-only List or Map types. StateFlow skips a value that equals the current one, so mutating a shared list in place produces no emission.
  • In Compose, collect with collectAsStateWithLifecycle() from lifecycle-runtime-compose. In a Fragment, wrap collection in repeatOnLifecycle(Lifecycle.State.STARTED) inside viewLifecycleOwner.lifecycleScope.
  • stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial) keeps a cold flow alive for 5 s after the last collector leaves, preventing upstream restarts on rotation.
  • Sealed UiState gives an exhaustive when in the UI; a flat data class makes copy() trivial. Pick per screen, not per project.
  • Events go up as function calls (fun loadMore()). State goes down as StateFlow. For one-off results (a snackbar message, moving on after a save), Google's guidance is to put them in UiState and have the UI call the ViewModel (onMessageShown()) to clear them after acting.
  • Test the ViewModel by injecting a fake repository and asserting on state.value or by collecting the flow inside runTest, with Dispatchers.setMain set to a test dispatcher. For SavedStateHandle, construct the ViewModel with a pre-populated handle.
  • collectAsStateWithLifecycle() stops collecting below STARTED (by default). Plain collectAsState() does not, so it keeps collecting while the app is in the background.
  • Do not wrap suspend calls in runCatching inside viewModelScope: it also catches CancellationException. Use try / catch and rethrow CancellationException.

Code example

This ViewModel exposes one immutable FeedUiState as a StateFlow and updates it atomically with update. The UI collects the flow; user actions call functions on the ViewModel.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
 
data class FeedItem(val id: Int, val title: String)
 
interface FeedRepository {
    suspend fun fetchFeed(page: Int, pageSize: Int): List<FeedItem> // main-safe
}
 
// Immutable UI state: val fields and read-only List
data class FeedUiState(
    val isLoading: Boolean = false,
    val items: List<FeedItem> = emptyList(),
    val error: String? = null,
    val hasMore: Boolean = true,
)
 
class FeedViewModel(private val repo: FeedRepository) : ViewModel() {
 
    // Private mutable, public read-only
    private val _state = MutableStateFlow(FeedUiState())
    val state: StateFlow<FeedUiState> = _state.asStateFlow()
 
    private var nextPage = 0
 
    init {
        loadMore() // runs once per ViewModel, not again after rotation
    }
 
    // Events go UP through function calls; state goes DOWN through StateFlow
    fun loadMore() {
        val current = _state.value
        if (current.isLoading || !current.hasMore) return
        // Set the flag before launching, so a second tap is ignored
        _state.update { it.copy(isLoading = true, error = null) }
        viewModelScope.launch {
            try {
                val page = repo.fetchFeed(page = nextPage, pageSize = PAGE_SIZE)
                nextPage++
                _state.update {
                    it.copy(isLoading = false, items = it.items + page, hasMore = page.size == PAGE_SIZE)
                }
            } catch (e: CancellationException) {
                throw e // the ViewModel was cleared: not an error
            } catch (e: Exception) {
                _state.update { it.copy(isLoading = false, error = e.message ?: "Unknown") }
            }
        }
    }
 
    private companion object {
        const val PAGE_SIZE = 20
    }
}
  • _state is private; the public surface is StateFlow via asStateFlow(), so no caller can write to it.
  • Every write uses update { it.copy(...) }, so a write from another coroutine is never lost.
  • The guard and the isLoading = true write both run synchronously on the main thread before the coroutine starts, so two quick calls cannot both start a request.
  • nextPage only advances on success, so calling loadMore() again after an error retries the same page. On error the loaded items stay on screen.
  • CancellationException is rethrown; runCatching would have swallowed it.

Run the idea in plain Kotlin

The same state holder with a fake repository of five posts, two per page. The second tap while loading is ignored, one request fails, and a retry continues from the same page.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

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

class FakeFeedRepository {
  var failNext = false
  private val all = (1..5).map { "post" + it }

  suspend fun fetchFeed(page: Int, pageSize: Int): List<String> {
      delay(100)
      if (failNext) {
          failNext = false
          throw IllegalStateException("offline")
      }
      return all.drop(page * pageSize).take(pageSize)
  }
}

class FeedHolder(private val scope: CoroutineScope, private val repo: FakeFeedRepository) {
  private val _state = MutableStateFlow(FeedUiState())
  val state: StateFlow<FeedUiState> = _state.asStateFlow()
  private var nextPage = 0

  fun loadMore() {
      val current = _state.value
      if (current.isLoading || !current.hasMore) {
          println("loadMore ignored")
          return
      }
      _state.update { it.copy(isLoading = true, error = null) }
      scope.launch {
          try {
              val page = repo.fetchFeed(nextPage, PAGE_SIZE)
              nextPage++
              _state.update {
                  it.copy(isLoading = false, items = it.items + page, hasMore = page.size == PAGE_SIZE)
              }
          } catch (e: CancellationException) {
              throw e
          } catch (e: Exception) {
              _state.update { it.copy(isLoading = false, error = e.message) }
          }
      }
  }

  companion object {
      const val PAGE_SIZE = 2
  }
}

fun main() = runBlocking {
  val repo = FakeFeedRepository()
  val holder = FeedHolder(this, repo)
  val ui = launch {
      holder.state.collect { s ->
          println("render: loading=" + s.isLoading + " items=" + s.items + " hasMore=" + s.hasMore + " error=" + s.error)
      }
  }
  yield()
  holder.loadMore()
  holder.loadMore() // second tap while loading
  delay(200)
  repo.failNext = true
  holder.loadMore()
  delay(200)
  holder.loadMore() // retry the same page
  delay(200)
  holder.loadMore()
  delay(200)
  holder.loadMore() // nothing left
  ui.cancel()
}

Expected output:

render: loading=false items=[] hasMore=true error=null
loadMore ignored
render: loading=true items=[] hasMore=true error=null
render: loading=false items=[post1, post2] hasMore=true error=null
render: loading=true items=[post1, post2] hasMore=true error=null
render: loading=false items=[post1, post2] hasMore=true error=offline
render: loading=true items=[post1, post2] hasMore=true error=null
render: loading=false items=[post1, post2, post3, post4] hasMore=true error=null
render: loading=true items=[post1, post2, post3, post4] hasMore=true error=null
render: loading=false items=[post1, post2, post3, post4, post5] hasMore=false error=null
loadMore ignored

In production

Stuck loading spinner after rotation
  • The Fragment started loading with lifecycleScope.launch { viewModel.load() }, where load() was a suspend function that set isLoading = true, fetched, and then set it back to false.
  • Rotating during the request destroyed the Fragment and cancelled its lifecycleScope, so the coroutine stopped after setting isLoading = true and never reset it.
  • The ViewModel survived the rotation, so the new Fragment collected the same StateFlow with isLoading = true, and the guard if (isLoading) return blocked every new load.
The fix
  • The team made load() a normal function that launches in viewModelScope, started once from init. Rotation no longer cancels the request.
  • The remaining cancellation path (the ViewModel cleared mid-request) resets isLoading in a finally block.
  • They added a unit test with a fake repository that never returns: start a load, cancel it, and assert state.value.isLoading == false.
Fragment leak from wrong collection scope
  • Memory profiler showed Fragment instances not being garbage-collected after the user navigated away.
  • The Fragment collected the ViewModel's StateFlow in lifecycleScope (the Fragment's full lifecycle) instead of viewLifecycleOwner.lifecycleScope.
  • In a ViewPager2, the view was destroyed but the Fragment was retained, so the collection kept a reference to the old view.
The fix
  • The team switched to repeatOnLifecycle(Lifecycle.State.STARTED) inside viewLifecycleOwner.lifecycleScope.
  • They set the binding to null in onDestroyView and ran LeakCanary in debug builds, so a retained view now shows up as a leak report.
  • A code-review checklist item now flags any lifecycleScope.launch in a Fragment that collects a flow and touches the view.

Common mistakes

  • Using _state.value = instead of update. Direct assignment is not atomic. Two coroutines that each read, modify, and write can overwrite each other's fields. Always use update { it.copy(...) }.
  • Collecting in GlobalScope or a custom CoroutineScope. Nothing cancels the collection, so it outlives the view and the ViewModel and leaks them. Use viewModelScope for the ViewModel side and viewLifecycleOwner.repeatOnLifecycle or collectAsStateWithLifecycle for the UI side.
  • Putting a message in UiState and never clearing it. StateFlow gives its latest value to every new collector, so after rotation the snackbar shows again. The UI must call onMessageShown() after showing it, and the ViewModel sets the field back to null.
  • Mutable fields in UiState. If you add to a MutableList inside the current state and set the same object again, the new value equals the old one, so StateFlow does not emit and the UI never re-renders. Use val fields and read-only collections, and build new lists with copy.
  • Exposing MutableStateFlow publicly. Any caller can write to it, bypassing the ViewModel's logic and invariants. Expose StateFlow via asStateFlow() and keep the MutableStateFlow private.
  • Wrapping suspend calls in runCatching. runCatching catches every Throwable, including the CancellationException thrown when viewModelScope is cancelled, so the coroutine reports a bogus error instead of stopping. Use try / catch, rethrow CancellationException, or catch only the exceptions you expect.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you expose UI state from a ViewModel?”

“What happens if you collect a StateFlow in the wrong lifecycle scope?”

“MVVM vs MVI: when would you choose each?”

“How do you test a ViewModel?”

Quiz

Which call makes a read-modify-write on a MutableStateFlow atomic?

What does SharingStarted.WhileSubscribed(5_000) do?

A ViewModel sets userMessage in UiState when a save fails. The UI shows a snackbar but never tells the ViewModel. What happens after a rotation?

Which collection method is lifecycle-aware in Compose?

0 of 4 answered

Mini task

Convert a LiveData ViewModel to StateFlow with update

You have a NewsViewModel that exposes LiveData<NewsUiState>. Convert it to the StateFlow pattern.

  1. Replace LiveData<NewsUiState> with MutableStateFlow<NewsUiState> (private) and expose StateFlow<NewsUiState> via asStateFlow().
  2. Replace every state.value = ... with _state.update { it.copy(...) }. Confirm no direct assignment remains.
  3. In the Composable, replace observeAsState() with collectAsStateWithLifecycle() from lifecycle-runtime-compose.
  4. In any Fragment that collects the flow, wrap the collection in repeatOnLifecycle(Lifecycle.State.STARTED) inside viewLifecycleOwner.lifecycleScope.
  5. Update the unit tests: replace InstantTaskExecutorRule and LiveData observers with runTest, a rule that calls Dispatchers.setMain(StandardTestDispatcher()), and assertions on state.value.
  6. Rotate the device in the emulator and confirm the UI state is correct after rotation.

Done condition: no LiveData import remains in the ViewModel, all unit tests pass, and the screen shows the correct state after a rotation.

Next: MVI in practice