Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 104 ยท Practice and Review

Practice: Architecture, Navigation and Data Exercises

Ten Android exercises with solutions on layers, ViewModel, UI state, StateFlow, the back stack, tabs and offline-first repositories, with runnable Kotlin stand-ins.

Architecture and navigation are the parts of Android where the mistakes are expensive: a ViewModel that holds a Context, an object passed through a route, a repository that loses data when the network drops. Reading the rules is easy. Applying them to a small problem is what makes them stick, and that is what this lesson gives you: ten exercises on layers, ViewModel, UI state, flows, the back stack and repositories.

The Android framework cannot run on this site, so every exercise has a real solution, shown as a read-only Android or Compose snippet, and a stand-in, a runnable Kotlin program (Kotlin 2.4 with coroutines on Piston) that models the same rule with plain classes. The stand-ins are not Android: they show the logic, and the text before each one says what is real and what is modeled. Try each task yourself first.

flowchart TD
    UI["UI layer<br/>(composables + ViewModel)"] --> D["Domain layer<br/>(optional use cases)"]
    D --> R["Data layer<br/>(repositories)"]
    R --> L["Local source<br/>(Room, DataStore)"]
    R --> N["Remote source<br/>(Retrofit)"]

The layers the exercises revolve around: dependencies point downward, data comes back up.

Background lessons: Architecture Layers, ViewModel, UI State and Events, StateFlow in Compose, Navigation Compose, Back Stack and Deep Links, Bottom Navigation and Offline-first.

Part 1: Layers, ViewModel and state

Exercise 1: split a screen into layers

Task. A screen shows "Hello, Ana!" for a user id. Today one class fetches the name, builds the sentence and formats it for the screen. Split it into a data source, an optional use case and a ViewModel, so the ViewModel can be tested with a fake.

Hint. The ViewModel should depend on an interface, never on a concrete network class.

Kotlin
// read-only example: needs Android
interface UserRepository {
    suspend fun userName(id: Int): String?
}

class GetGreeting(private val users: UserRepository) {
    suspend operator fun invoke(id: Int): String =
        users.userName(id)?.let { "Hello, $it!" } ?: "Hello, guest!"
}

class GreetingViewModel(private val getGreeting: GetGreeting) : ViewModel() {
    private val _text = MutableStateFlow("")
    val text: StateFlow<String> = _text.asStateFlow()

    fun load(id: Int) {
        viewModelScope.launch { _text.value = getGreeting(id) }
    }
}

The stand-in uses the same shape with blocking functions instead of suspending ones, and a fake repository.

Kotlin Solution 1: three layers and a fake (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Swapping FakeUserRepository for a Room- or Retrofit-backed one changes nothing above it. That is the point of the split.

Exercise 2: what survives rotation?

Task. Rotation destroys and recreates the Activity. Which of these survive: a field in the Activity, a field in a ViewModel, a remember value, a rememberSaveable value? Show it.

Hint. The ViewModel lives in a store that outlives the Activity instance. rememberSaveable goes through a saved-state bundle.

Kotlin
// read-only example: needs Android
class CounterViewModel : ViewModel() {
    var taps by mutableIntStateOf(0)
        private set
    fun tap() { taps++ }
}

@Composable
fun CounterScreen(vm: CounterViewModel = viewModel()) {
    var expanded by rememberSaveable { mutableStateOf(false) }   // survives rotation
    var hover by remember { mutableStateOf(false) }              // lost on rotation
    /* UI uses vm.taps, expanded, hover */
}
Kotlin Solution 2: a store that outlives the activity (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only the ViewModel value and the saved value come back. The plain field and the remember value start again from their defaults.

Exercise 3: model a screen as one UI state

Task. A list screen can be loading, show items, or show an error with a retry button. Model it so impossible combinations (a spinner and an error at once) cannot exist, and write a reducer that handles these events: Load, Loaded(items), Failed(message).

Hint. Use a sealed interface for the state and a when with no else.

Kotlin
// read-only example: needs Android
sealed interface ListUiState {
    data object Loading : ListUiState
    data class Content(val items: List<String>) : ListUiState
    data class Error(val message: String) : ListUiState
}
Kotlin Solution 3: sealed state and a reducer (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because the reducer is a pure function, a unit test is just "given this state and this event, expect that state".

Exercise 4: expose a read-only StateFlow

Task. A ViewModel keeps a counter in a MutableStateFlow. The UI must be able to observe it but never set it. Show that a StateFlow keeps only the latest value and ignores a write of an equal value.

Hint. Keep the mutable flow private and expose asStateFlow().

Kotlin
// read-only example: needs Android
class CounterViewModel : ViewModel() {
    private val _count = MutableStateFlow(0)
    val count: StateFlow<Int> = _count.asStateFlow()

    fun increment() = _count.update { it + 1 }
}

// in the composable
val count by vm.count.collectAsStateWithLifecycle()

collectAsStateWithLifecycle stops collecting when the screen is in the background, which saves work.

Kotlin Solution 4: StateFlow keeps the latest, skips equals (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Part 2: Navigation

Exercise 5: simulate the back stack

Task. Implement navigate, back and navigateAndClear for a back stack of route names. Then run this journey: Home, then List, then Detail, then Detail again (it should not be pushed twice), then Login while clearing everything up to and including Home.

Hint. launchSingleTop means "do not push if the top is already this route". popUpTo(route) { inclusive = true } removes entries down to and including that route.

Kotlin
// read-only example: needs Compose and Navigation
navController.navigate(Detail(id = 7)) { launchSingleTop = true }

navController.navigate(Login) {
    popUpTo(Home) { inclusive = true }
}
Kotlin Solution 5: a back stack with singleTop and popUpTo (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the login journey there is nothing to go back to: the back stack holds only Login, so back leaves the app.

Exercise 6: pass an id, not an object

Task. A route is written detail/42?tab=comments. Write a small parser that splits the path and the query, then show the detail screen loading the item by id from a repository. Explain why you should not pass the whole object through the route.

Hint. Routes are strings (or serialized values) with a size limit, and they are restored after process death. Large or live objects do not belong there.

Kotlin
// read-only example: needs Compose and Navigation
@Serializable data class Detail(val id: Int, val tab: String = "info")

composable<Detail> { entry ->
    val route = entry.toRoute<Detail>()
    DetailScreen(id = route.id, tab = route.tab)
}
Kotlin Solution 6: parse the route, load by id (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The screen survives process death because the id is enough to rebuild everything. A passed object would be gone.

Exercise 7: one back stack per tab

Task. A bottom bar has three tabs, and each keeps its own stack. Rules: switching tabs keeps each stack; back pops inside the current tab; back at the root of a non-start tab returns to the start tab; back at the root of the start tab leaves the app.

Hint. Keep a map from tab to stack and a pointer to the current tab.

Kotlin
// read-only example: needs Compose and Navigation
navController.navigate(tab.route) {
    popUpTo(navController.graph.findStartDestination().id) { saveState = true }
    launchSingleTop = true
    restoreState = true
}
Kotlin Solution 7: a stack per tab (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The stand-in is a model: the real library also saves and restores each tab's state objects, not only the destinations.

Part 3: Flows and data

Exercise 8: search as you type

Task. A query arrives as the user types. Wait until typing pauses for 50 ms, ignore repeats, and cancel the previous search when a new one starts. Which operators do that?

Hint. debounce, distinctUntilChanged and flatMapLatest.

Kotlin
// read-only example: needs Android
val results: StateFlow<List<Item>> = query
    .debounce(300)
    .distinctUntilChanged()
    .flatMapLatest { text -> repository.search(text) }
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

The stand-in uses short real delays and a fake search, so it prints the same lines every run.

Kotlin Solution 8: debounce, distinct and flatMapLatest (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only two searches run: for the text after the first pause and for the final word. The intermediate k and ko were swallowed by the debounce, and the repeated kot was filtered.

Exercise 9: a repository with a cache and a refresh

Task. A repository should return cached data immediately, fetch fresh data on refresh(), and update the cache. Count how many times the slow remote source is called.

Hint. The repository is the single place that decides between local and remote.

Kotlin
// read-only example: needs Android
class ArticleRepository(
    private val dao: ArticleDao,
    private val api: ArticleApi
) {
    val articles: Flow<List<Article>> = dao.observeAll()

    suspend fun refresh() {
        dao.replaceAll(api.fetchArticles().map { it.toEntity() })
    }
}
Kotlin Solution 9: cache first, refresh on demand (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Reads cost nothing because they come from the cache. Only the explicit refresh() touches the network.

Exercise 10: keep working offline

Task. Extend the repository so a failed refresh keeps the old cached data and reports the failure instead of crashing. Show three states: online refresh, offline refresh with a cache, and offline refresh with an empty cache.

Hint. Return a Result from refresh(), and let the UI keep observing the cache.

Kotlin
// read-only example: needs Android
suspend fun refresh(): Result<Unit> = runCatching {
    dao.replaceAll(api.fetchArticles().map { it.toEntity() })
}
Kotlin Solution 10: offline-first with a Result (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The cache is the single source of truth: the network can only update it, never replace it with an error.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a ViewModel depend on a repository interface rather than a concrete class?

    Depending on an abstraction decouples the layers. A fake in tests and a swapped data source both leave the ViewModel unchanged.
  2. 2. After a screen rotation, which value is lost?

    Rotation recreates the Activity. The ViewModel store and saved state survive, but a plain remember value is rebuilt from its default.
  3. 3. What does launchSingleTop = true do?

    With launchSingleTop, navigating to the destination that is already on top reuses it instead of adding a duplicate.
  4. 4. Why pass an id rather than a whole object through a navigation route?

    A route should carry a small, serializable identity. The destination loads the data from a repository, which also works after the process was killed.
  5. 5. In an offline-first design, what should a failed network refresh do?

    The local store is the single source of truth. The network updates it when it can. When it cannot, the existing data stays visible and the error becomes a message.

Summary

  • Keep UI, domain and data in separate layers, with interfaces between them so fakes can replace real sources.
  • A ViewModel survives rotation; plain fields and remember values do not; rememberSaveable goes through saved state.
  • Model a screen as one sealed UI state and change it with a pure reducer.
  • Expose StateFlow read-only with asStateFlow(); it keeps the latest value and ignores equal writes.
  • The back stack is a list: launchSingleTop avoids duplicates and popUpTo removes entries.
  • Pass ids through routes, never objects, and give each bottom-bar tab its own stack.
  • Use debounce, distinctUntilChanged and flatMapLatest for search as you type.
  • A repository decides between cache and network; offline-first means failures never erase data.
  • The Android snippets are read-only; the TryIt blocks are Kotlin stand-ins for the logic.

Next: Android Interview Questions