Android + Kotlin Notes

Project setup

gradle/libs.versions.toml

Pinned for Kotlin 2.0.21. Don't accept "newer version" hints. Set lifecycleRuntimeKtx = "2.8.7".

[versions]
lifecycle = "2.8.7"
navigationCompose = "2.8.9"
retrofit = "2.11.0"
okhttp = "4.12.0"
coil = "3.0.4"

[libraries]
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
coil-network-okhttp = { group = "io.coil-kt.coil3", name = "coil-network-okhttp", version.ref = "coil" }

app/build.gradle.kts → dependencies { }

implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.retrofit)
implementation(libs.retrofit.converter.gson)
implementation(libs.okhttp.logging)
implementation(libs.coil.compose)
implementation(libs.coil.network.okhttp)   // Coil 3 shows nothing for URLs without this

AndroidManifest.xml (above <application>)

<uses-permission android:name="android.permission.INTERNET" />
<!-- only if forced onto http://, add to <application>: android:usesCleartextTraffic="true" -->

Android Studio settings

Git reset between runs

git tag skeleton          # once
git reset --hard skeleton && git clean -fd

.gitignore should include .kotlin and .idea.

Folder layout

com.example.skeleton/
├── MainActivity.kt           ← setContent, theme, Scaffold, NavHost. No data.
├── data/
│   ├── ApiClient.kt          ← Retrofit + OkHttp
│   ├── User.kt               ← models (data classes)
│   ├── UserApi.kt            ← Retrofit interface
│   └── UserRepository.kt     ← single source of data
└── ui/
    ├── UiState.kt
    ├── theme/
    ├── list/   ListViewModel.kt, ListScreen.kt
    └── detail/ DetailViewModel.kt, DetailScreen.kt

Imports (paste at the top of any UI file)

import androidx.compose.foundation.*                 // clickable, background, Image
import androidx.compose.foundation.layout.*          // Row, Column, Box, Spacer, padding, size, width, fillMaxWidth
import androidx.compose.foundation.lazy.*            // LazyColumn, items, item
import androidx.compose.material3.*                  // Text, Button, Scaffold, TopAppBar, MaterialTheme, FilterChip
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*      // Icons.Filled.Search, Star, Refresh
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.*                    // Composable, remember, mutableStateOf, getValue, setValue, LaunchedEffect
import androidx.compose.ui.*                         // Modifier, Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.*                    // dp, sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.AsyncImage

ViewModel files: androidx.lifecycle.ViewModel, androidx.lifecycle.viewModelScope, kotlinx.coroutines.flow.*, kotlinx.coroutines.launch, kotlinx.coroutines.delay, kotlinx.coroutines.isActive.
Retrofit: retrofit2.http.GET, retrofit2.http.Path, retrofit2.http.Query, retrofit2.HttpException. Gson: com.google.gson.annotations.SerializedName.

Core template: fetch → list (Problem 2A)

Every problem is this template with a different model and endpoint.

data/ApiClient.kt

package com.example.skeleton.data

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ApiClient {
    private val logging = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY            // full JSON in Logcat
    }
    private val client = OkHttpClient.Builder().addInterceptor(logging).build()

    fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)                                    // MUST end with "/"
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

ui/UiState.kt

package com.example.skeleton.ui

sealed interface UiState<out T> {
    data object Loading : UiState<Nothing>
    data class Success<T>(val data: T) : UiState<T>
    data class Error(val message: String) : UiState<Nothing>
}

Model + API + Repository (data/)

data class User(
    val id: Int,
    val name: String,
    val email: String,
    val company: Company
)
data class Company(val name: String)

interface UserApi {
    @GET("users")
    suspend fun getUsers(): List<User>

    @GET("users/{id}/posts")
    suspend fun getPosts(@Path("id") userId: Int): List<Post>
}

class UserRepository {
    private val api: UserApi = ApiClient
        .retrofit("https://jsonplaceholder.typicode.com/")
        .create(UserApi::class.java)

    suspend fun getUsers(): List<User> = api.getUsers()
    suspend fun getPosts(userId: Int): List<Post> = api.getPosts(userId)
}

ViewModel

class UserListViewModel : ViewModel() {
    private val repository = UserRepository()

    private val _state = MutableStateFlow<UiState<List<User>>>(UiState.Loading)
    val state: StateFlow<UiState<List<User>>> = _state.asStateFlow()

    init { load() }                                   // once; rotation reuses this ViewModel

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getUsers())
            } catch (e: Exception) {
                UiState.Error(e.message ?: "Something went wrong")
            }
        }
    }
}

Screen

@Composable
fun UserListScreen(
    onUserClick: (Int) -> Unit,
    modifier: Modifier = Modifier,
    viewModel: UserListViewModel = viewModel()
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        when (val s = state) {                          // local val → smart cast works
            UiState.Loading -> CircularProgressIndicator()
            is UiState.Error -> ErrorView(s.message, onRetry = viewModel::load)
            is UiState.Success ->
                if (s.data.isEmpty()) Text("No users")
                else LazyColumn(Modifier.fillMaxSize()) {
                    items(s.data, key = { it.id }) { user ->
                        UserRow(user, Modifier.clickable { onUserClick(user.id) })
                        HorizontalDivider()
                    }
                }
        }
    }
}

@Composable
fun UserRow(user: User, modifier: Modifier = Modifier) {
    Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
        Text(user.name, fontWeight = FontWeight.Bold)
        Text(user.email, style = MaterialTheme.typography.bodySmall)
        Text(user.company.name, style = MaterialTheme.typography.bodySmall)
    }
}

@Composable
fun ErrorView(message: String, onRetry: () -> Unit) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(message)
        Spacer(Modifier.height(8.dp))
        Button(onClick = onRetry) { Text("Retry") }
    }
}

Row with icon + price on the right (Problem 1A pattern)

@Composable
fun StockRow(stock: Stock, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        AsyncImage(model = stock.url, contentDescription = stock.name, modifier = Modifier.size(32.dp))
        Spacer(Modifier.width(12.dp))
        Column {
            Text(stock.symbol, fontWeight = FontWeight.Bold)
            Text(stock.name, style = MaterialTheme.typography.bodySmall)
        }
        Spacer(Modifier.weight(1f))                    // pushes the price to the right edge
        Column(horizontalAlignment = Alignment.End) {
            Text("$" + "%.2f".format(stock.price))
            Text(
                (if (stock.change >= 0) "+" else "") + "%.2f%%".format(stock.change),
                color = if (stock.change >= 0) Color(0xFF00C805) else Color.Red
            )
        }
    }
}

JSON → data classes

JSON looks likeKotlin
[ {...}, {...} ] (top-level array)suspend fun get(): List<Item>
{ "results": [ ... ] } (wrapped)data class Resp(val results: List<Item>) → suspend fun get(): Resp
"current_price": 1.2 (snake_case)@SerializedName("current_price") val currentPrice: Double
"quotes": { "USD": { "price": 1 } }One data class per object level; @SerializedName("USD") val usd: UsdQuote
Field sometimes null or missingMake it nullable: val change: Double? (Gson leaves null even in non-null fields)
"lat": "-37.31" (number as string)val lat: String, then lat.toDoubleOrNull()
Fields you don't needLeave them out. Gson ignores undeclared keys.
?vs_currency=usd@Query("vs_currency") currency: String = "usd"
/users/{id}/posts@GET("users/{id}/posts") suspend fun posts(@Path("id") id: Int)

Models use val, never var. To change one, make a new object with copy() so the StateFlow emits.

Extensions

Search + sort: derive the visible list (4A, 4B, 4G)

enum class SortOrder { RANK, PRICE, CHANGE }

class CoinListViewModel : ViewModel() {
    private val repository = CoinRepository()

    private val _state = MutableStateFlow<UiState<List<Coin>>>(UiState.Loading)
    private val _query = MutableStateFlow("")
    private val _sort = MutableStateFlow(SortOrder.RANK)
    val query: StateFlow<String> = _query.asStateFlow()
    val sort: StateFlow<SortOrder> = _sort.asStateFlow()

    // What the screen shows = fetched data + query + sort
    val visible: StateFlow<UiState<List<Coin>>> =
        combine(_state, _query, _sort) { state, q, sort ->
            if (state !is UiState.Success) state
            else UiState.Success(
                state.data
                    .filter { q.isBlank() || it.name.contains(q, true) || it.symbol.contains(q, true) }
                    .let { list ->
                        when (sort) {
                            SortOrder.RANK -> list.sortedBy { it.rank }
                            SortOrder.PRICE -> list.sortedByDescending { it.price }
                            SortOrder.CHANGE -> list.sortedByDescending { it.change }
                        }
                    }
            )
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)

    fun onQueryChange(q: String) { _query.value = q }
    fun onSortChange(s: SortOrder) { _sort.value = s }

    init { load() }
    fun load() { /* same as the core template, writing to _state */ }
}
// Screen: search field + chips above the list
val query by viewModel.query.collectAsStateWithLifecycle()
val sort by viewModel.sort.collectAsStateWithLifecycle()

Column(modifier.fillMaxSize()) {
    OutlinedTextField(
        value = query,                                // what the field shows
        onValueChange = viewModel::onQueryChange,     // called with the new text on every keystroke
        label = { Text("Search") },
        leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
        singleLine = true,
        modifier = Modifier.fillMaxWidth().padding(16.dp)
    )
    Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        SortOrder.entries.forEach { option ->
            FilterChip(
                selected = sort == option,
                onClick = { viewModel.onSortChange(option) },
                label = { Text(option.name.lowercase().replaceFirstChar { it.uppercase() }) }
            )
        }
    }
    // then the Box + when(visible) block; empty Success → Text("No coins match \"$query\"")
}

4C Retry

The error state shows Button(onClick = viewModel::load). Test with airplane mode.

4D Pull to refresh

@OptIn(ExperimentalMaterial3Api::class)
PullToRefreshBox(
    isRefreshing = isRefreshing,          // separate StateFlow<Boolean>
    onRefresh = viewModel::refresh
) { LazyColumn { ... } }

Keep the old list while refreshing. Don't switch to Loading.

4E Auto-refresh every 30 s

init {
    viewModelScope.launch {
        while (isActive) { load(); delay(30_000) }
    }
}

It stops automatically when the ViewModel is cleared.

4F Favorites pinned to top

private val _favs = MutableStateFlow<Set<String>>(emptySet())
fun toggleFav(id: String) =
    _favs.update { if (id in it) it - id else it + id }
// in combine: .sortedByDescending { it.id in favs }

Timestamp header

val time = SimpleDateFormat("HH:mm", Locale.US).format(Date())
LazyColumn { item { Text("Updated $time") } ; items(...) }

HTTP 429 / status codes

} catch (e: HttpException) {
    UiState.Error(if (e.code() == 429)
        "Rate limited (429). Try again in a minute."
        else "Server error ${e.code()}")
} catch (e: Exception) { ... }

Put HttpException before Exception.

Live-updating lists (Level 5)

5A Ticker: prices change every second, pause/resume, alerts

data class Quote(val symbol: String, val price: Double, val previous: Double)

class TickerViewModel : ViewModel() {
    private val _quotes = MutableStateFlow(
        listOf("AAPL", "NVDA", "HOOD", "TSLA", "AMZN").map { Quote(it, 100.0, 100.0) }
    )
    val quotes: StateFlow<List<Quote>> = _quotes.asStateFlow()

    private val _running = MutableStateFlow(false)
    val running: StateFlow<Boolean> = _running.asStateFlow()
    private var job: Job? = null

    init { start() }

    fun start() {
        if (job?.isActive == true) return              // never two loops
        _running.value = true
        job = viewModelScope.launch {
            while (isActive) {
                delay(1_000)
                _quotes.update { list ->
                    list.map { q ->
                        q.copy(previous = q.price,
                               price = q.price * (1 + Random.nextDouble(-0.01, 0.01)))
                    }
                }
            }
        }
    }

    fun pause() { job?.cancel(); _running.value = false }
}
// Row color
val color = when {
    q.price > q.previous -> Color(0xFF00C805)
    q.price < q.previous -> Color.Red
    else -> MaterialTheme.colorScheme.onSurface
}
// List: items(quotes, key = { it.symbol }) { ... }   ← stable keys, no flicker
// Button: if (running) Button(viewModel::pause) { Text("Pause") } else Button(viewModel::start) { Text("Resume") }

Alerts extension: store targets: Map<String, Double> and an alerted: Set<String>. In the loop, when the price crosses the target and the symbol isn't in alerted, emit to a MutableSharedFlow<String>. The screen collects it in LaunchedEffect(Unit) and calls snackbarHostState.showSnackbar(msg).

Imports: kotlinx.coroutines.Job, kotlinx.coroutines.flow.update, kotlin.random.Random.

5B Countdown timers

data class Timer(val id: Int, val remaining: Int, val running: Boolean = true)

class TimersViewModel : ViewModel() {
    private var nextId = 0
    private val _timers = MutableStateFlow<List<Timer>>(emptyList())
    val timers: StateFlow<List<Timer>> = _timers.asStateFlow()

    init {
        viewModelScope.launch {                        // ONE loop ticks every running timer
            while (isActive) {
                delay(1_000)
                _timers.update { list ->
                    list.map { if (it.running && it.remaining > 0) it.copy(remaining = it.remaining - 1) else it }
                }
            }
        }
    }
    fun add() = _timers.update { it + Timer(nextId++, 30) }
    fun remove(id: Int) = _timers.update { list -> list.filterNot { it.id == id } }
    fun toggle(id: Int) = _timers.update { list ->
        list.map { if (it.id == id) it.copy(running = !it.running) else it }
    }
}
// Row text: if (t.remaining == 0) "Done" else "${t.remaining}s"

Problems and full solutions

Every problem uses the three shared files plus its own files. Each file starts with its package line; where you see // + UI imports, // + VM imports or // + MainActivity imports, paste that block from Shared below. Reset with git reset --hard skeleton && git clean -fd between problems, since some files are reused with different contents.

Shared: import blocks + files every problem uses

UI imports

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.*
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.AsyncImage
import com.example.skeleton.data.*
import com.example.skeleton.ui.*

VM imports

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.skeleton.data.*
import com.example.skeleton.ui.UiState
import com.example.skeleton.ui.toMessage
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

MainActivity imports

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.skeleton.ui.*
import com.example.skeleton.ui.theme.SkeletonTheme

data/ApiClient.kt

package com.example.skeleton.data

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ApiClient {
    private val logging = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }
    private val client = OkHttpClient.Builder().addInterceptor(logging).build()

    fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)                       // must end with "/"
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

ui/UiState.kt

package com.example.skeleton.ui

sealed interface UiState<out T> {
    data object Loading : UiState<Nothing>
    data class Success<T>(val data: T) : UiState<T>
    data class Error(val message: String) : UiState<Nothing>
}

ui/Common.kt

package com.example.skeleton.ui

// + UI imports
import kotlin.math.abs

val GainGreen = Color(0xFF00C805)

fun formatPrice(price: Double): String = "$" + "%,.2f".format(price)

fun Throwable.toMessage(): String = when (this) {
    is retrofit2.HttpException ->
        if (code() == 429) "Rate limited (429). Try again in a minute." else "Server error (${code()})"
    is java.io.IOException -> "No internet connection"
    else -> message ?: "Something went wrong"
}

@Composable
fun ChangeText(percent: Double?, modifier: Modifier = Modifier) {
    if (percent == null) {
        Text("—", modifier = modifier)
        return
    }
    Text(
        text = (if (percent >= 0) "+" else "-") + "%.2f%%".format(abs(percent)),
        color = if (percent >= 0) GainGreen else Color.Red,
        style = MaterialTheme.typography.bodySmall,
        modifier = modifier
    )
}

@Composable
fun LoadingView(modifier: Modifier = Modifier) {
    Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator()
    }
}

@Composable
fun ErrorView(message: String, onRetry: () -> Unit, modifier: Modifier = Modifier) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(message)
        Spacer(Modifier.height(8.dp))
        Button(onClick = onRetry) { Text("Retry") }
    }
}

@Composable
fun EmptyView(message: String, modifier: Modifier = Modifier) {
    Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text(message)
    }
}

// Page frame: top bar (with optional back arrow), optional snackbar and FAB.
// content receives a Modifier that already holds the Scaffold padding.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppScaffold(
    title: String,
    onBack: (() -> Unit)? = null,
    snackbarHostState: SnackbarHostState? = null,
    floatingActionButton: @Composable () -> Unit = {},
    content: @Composable (Modifier) -> Unit
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(title) },
                navigationIcon = {
                    if (onBack != null) {
                        IconButton(onClick = onBack) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                        }
                    }
                }
            )
        },
        snackbarHost = { if (snackbarHostState != null) SnackbarHost(snackbarHostState) },
        floatingActionButton = floatingActionButton
    ) { innerPadding ->
        content(Modifier.padding(innerPadding))
    }
}
0A Blank-project sprint (< 8 min)
  1. File → New Project → Empty Activity (Compose), Kotlin DSL, minSdk 26. Run once.
  2. Paste the toml and gradle lines from Setup, set lifecycleRuntimeKtx = "2.8.7", and sync.
  3. Add the INTERNET permission. Add the three shared files. Run.
1A Watchlist from hardcoded data (12 min)

Spec: show five stocks with symbol (bold), name, and price on the right. Extension: change in green/red.

data/Stock.kt

package com.example.skeleton.data

data class Stock(
    val symbol: String,
    val name: String,
    val price: Double,
    val changePercent: Double
)

data/StockRepository.kt

package com.example.skeleton.data

class StockRepository {
    fun getStocks(): List<Stock> = listOf(
        Stock("AAPL", "Apple", 187.42, 1.20),
        Stock("HOOD", "Robinhood", 40.10, -0.85),
        Stock("NVDA", "Nvidia", 300.00, 2.30),
        Stock("TSLA", "Tesla", 250.00, -3.10),
        Stock("GOOGL", "Alphabet", 170.00, 0.40)
    )
}

ui/watchlist/WatchlistViewModel.kt

package com.example.skeleton.ui.watchlist

// + VM imports

class WatchlistViewModel : ViewModel() {
    private val repository = StockRepository()

    private val _stocks = MutableStateFlow<List<Stock>>(emptyList())
    val stocks: StateFlow<List<Stock>> = _stocks.asStateFlow()

    init {
        _stocks.value = repository.getStocks()
    }
}

ui/watchlist/WatchlistScreen.kt

package com.example.skeleton.ui.watchlist

// + UI imports

@Composable
fun WatchlistScreen(modifier: Modifier = Modifier, viewModel: WatchlistViewModel = viewModel()) {
    val stocks by viewModel.stocks.collectAsStateWithLifecycle()

    LazyColumn(modifier = modifier.fillMaxSize()) {
        items(stocks, key = { it.symbol }) { stock ->
            StockRow(stock)
            HorizontalDivider()
        }
    }
}

@Composable
fun StockRow(stock: Stock, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            Text(stock.symbol, fontWeight = FontWeight.Bold)
            Text(stock.name, style = MaterialTheme.typography.bodySmall)
        }
        Spacer(Modifier.weight(1f))
        Column(horizontalAlignment = Alignment.End) {
            Text(formatPrice(stock.price))
            ChangeText(stock.changePercent)          // extension: green / red
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.watchlist.WatchlistScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                AppScaffold(title = "Watchlist") { modifier ->
                    WatchlistScreen(modifier = modifier)
                }
            }
        }
    }
}
2A User directory (20 min)

API: https://jsonplaceholder.typicode.com/users. Show name, email, company. Loading, error + retry, empty state.

data/User.kt

package com.example.skeleton.data

data class User(
    val id: Int,
    val name: String,
    val email: String,
    val phone: String,
    val website: String,
    val address: Address,
    val company: Company
)

data class Address(val city: String)

data class Company(val name: String)

data/UserApi.kt

package com.example.skeleton.data

import retrofit2.http.GET

interface UserApi {
    @GET("users")
    suspend fun getUsers(): List<User>
}

data/UserRepository.kt

package com.example.skeleton.data

class UserRepository {
    private val api: UserApi = ApiClient
        .retrofit("https://jsonplaceholder.typicode.com/")
        .create(UserApi::class.java)

    suspend fun getUsers(): List<User> = api.getUsers()
}

ui/users/UserListViewModel.kt

package com.example.skeleton.ui.users

// + VM imports

class UserListViewModel : ViewModel() {
    private val repository = UserRepository()

    private val _state = MutableStateFlow<UiState<List<User>>>(UiState.Loading)
    val state: StateFlow<UiState<List<User>>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getUsers())
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/users/UserListScreen.kt

package com.example.skeleton.ui.users

// + UI imports

@Composable
fun UserListScreen(
    onUserClick: (Int) -> Unit = {},
    modifier: Modifier = Modifier,
    viewModel: UserListViewModel = viewModel()
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val s = state) {
        UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
        is UiState.Success ->
            if (s.data.isEmpty()) {
                EmptyView("No users", modifier)          // extension
            } else {
                LazyColumn(modifier.fillMaxSize()) {
                    items(s.data, key = { it.id }) { user ->
                        UserRow(user, Modifier.clickable { onUserClick(user.id) })
                        HorizontalDivider()
                    }
                }
            }
    }
}

@Composable
fun UserRow(user: User, modifier: Modifier = Modifier) {
    Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
        Text(user.name, fontWeight = FontWeight.Bold)
        Text(user.email, style = MaterialTheme.typography.bodySmall)
        Text(user.company.name, style = MaterialTheme.typography.bodySmall)
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.users.UserListScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                AppScaffold(title = "Users") { modifier ->
                    UserListScreen(modifier = modifier)
                }
            }
        }
    }
}

Test: airplane mode → error + Retry. Rotate → no second request in Logcat.

2B Crypto list, nested price — CoinPaprika (20 min)

API: https://api.coinpaprika.com/v1/tickers (~2,000 coins, price under quotes.USD). Top 50 by rank. Extension: "Updated HH:mm" header.

data/Ticker.kt

package com.example.skeleton.data

import com.google.gson.annotations.SerializedName

data class Ticker(
    val id: String,
    val name: String,
    val symbol: String,
    val rank: Int,
    val quotes: Quotes
)

data class Quotes(
    @SerializedName("USD") val usd: UsdQuote
)

data class UsdQuote(
    val price: Double,
    @SerializedName("percent_change_24h") val change24h: Double?,
    @SerializedName("market_cap") val marketCap: Double?
)

data/PaprikaApi.kt

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Path

interface PaprikaApi {
    @GET("v1/tickers")
    suspend fun getTickers(): List<Ticker>

    @GET("v1/tickers/{id}")
    suspend fun getTicker(@Path("id") id: String): Ticker
}

data/TickerRepository.kt

package com.example.skeleton.data

class TickerRepository {
    private val api: PaprikaApi = ApiClient
        .retrofit("https://api.coinpaprika.com/")
        .create(PaprikaApi::class.java)

    suspend fun getTop50(): List<Ticker> =
        api.getTickers().filter { it.rank > 0 }.sortedBy { it.rank }.take(50)

    suspend fun getTicker(id: String): Ticker = api.getTicker(id)
}

ui/tickers/TickerListViewModel.kt

package com.example.skeleton.ui.tickers

// + VM imports
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class TickerListViewModel : ViewModel() {
    private val repository = TickerRepository()

    private val _state = MutableStateFlow<UiState<List<Ticker>>>(UiState.Loading)
    val state: StateFlow<UiState<List<Ticker>>> = _state.asStateFlow()

    private val _updatedAt = MutableStateFlow("")
    val updatedAt: StateFlow<String> = _updatedAt.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                val tickers = repository.getTop50()
                _updatedAt.value = SimpleDateFormat("HH:mm", Locale.US).format(Date())
                UiState.Success(tickers)
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/tickers/TickerListScreen.kt

package com.example.skeleton.ui.tickers

// + UI imports

@Composable
fun TickerListScreen(
    onTickerClick: (String) -> Unit = {},
    modifier: Modifier = Modifier,
    viewModel: TickerListViewModel = viewModel()
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val updatedAt by viewModel.updatedAt.collectAsStateWithLifecycle()

    when (val s = state) {
        UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
        is UiState.Success -> LazyColumn(modifier.fillMaxSize()) {
            item {                                       // extension
                Text(
                    "Updated $updatedAt",
                    style = MaterialTheme.typography.labelMedium,
                    modifier = Modifier.padding(16.dp)
                )
            }
            items(s.data, key = { it.id }) { ticker ->
                TickerRow(ticker, Modifier.clickable { onTickerClick(ticker.id) })
                HorizontalDivider()
            }
        }
    }
}

@Composable
fun TickerRow(ticker: Ticker, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            "${ticker.rank}",
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier.width(32.dp)
        )
        Column {
            Text(ticker.symbol, fontWeight = FontWeight.Bold)
            Text(ticker.name, style = MaterialTheme.typography.bodySmall)
        }
        Spacer(Modifier.weight(1f))
        Column(horizontalAlignment = Alignment.End) {
            Text(formatPrice(ticker.quotes.usd.price))
            ChangeText(ticker.quotes.usd.change24h)
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.tickers.TickerListScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                AppScaffold(title = "Crypto") { modifier ->
                    TickerListScreen(modifier = modifier)
                }
            }
        }
    }
}
2C Crypto markets with icons + 429 — CoinGecko (20 min)

API: https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=50. Keyless limit ≈ 5 calls/min, so you will see 429 (handled by toMessage()).

data/Coin.kt

package com.example.skeleton.data

import com.google.gson.annotations.SerializedName

data class Coin(
    val id: String,
    val symbol: String,
    val name: String,
    val image: String,
    @SerializedName("current_price") val currentPrice: Double,
    @SerializedName("price_change_percentage_24h") val change24h: Double?   // sometimes null
)

data/GeckoApi.kt

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Query

interface GeckoApi {
    @GET("api/v3/coins/markets")
    suspend fun getMarkets(
        @Query("vs_currency") currency: String = "usd",
        @Query("per_page") perPage: Int = 50
    ): List<Coin>
}

data/CoinRepository.kt

package com.example.skeleton.data

class CoinRepository {
    private val api: GeckoApi = ApiClient
        .retrofit("https://api.coingecko.com/")
        .create(GeckoApi::class.java)

    suspend fun getCoins(): List<Coin> = api.getMarkets()
}

ui/coins/CoinListViewModel.kt

package com.example.skeleton.ui.coins

// + VM imports

class CoinListViewModel : ViewModel() {
    private val repository = CoinRepository()

    private val _state = MutableStateFlow<UiState<List<Coin>>>(UiState.Loading)
    val state: StateFlow<UiState<List<Coin>>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getCoins())
            } catch (e: Exception) {
                UiState.Error(e.toMessage())             // 429 → "Rate limited (429)..."
            }
        }
    }
}

ui/coins/CoinListScreen.kt

package com.example.skeleton.ui.coins

// + UI imports

@Composable
fun CoinListScreen(modifier: Modifier = Modifier, viewModel: CoinListViewModel = viewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val s = state) {
        UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
        is UiState.Success -> LazyColumn(modifier.fillMaxSize()) {
            items(s.data, key = { it.id }) { coin ->
                CoinRow(coin)
                HorizontalDivider()
            }
        }
    }
}

@Composable
fun CoinRow(coin: Coin, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        AsyncImage(
            model = coin.image,
            contentDescription = coin.name,
            modifier = Modifier.size(32.dp)
        )
        Spacer(Modifier.width(12.dp))
        Column {
            Text(coin.name, fontWeight = FontWeight.Bold)
            Text(coin.symbol.uppercase(), style = MaterialTheme.typography.bodySmall)
        }
        Spacer(Modifier.weight(1f))
        Column(horizontalAlignment = Alignment.End) {
            Text(formatPrice(coin.currentPrice))
            ChangeText(coin.change24h)
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.coins.CoinListScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                AppScaffold(title = "Markets") { modifier ->
                    CoinListScreen(modifier = modifier)
                }
            }
        }
    }
}
3A User detail with a second request (15 min)

Builds on 2A. Keep User.kt, UserListViewModel.kt and UserListScreen.kt from 2A; replace/add the files below. Tap user → profile (from the already-loaded list) + their posts (second request). Extension: tap a post → its body.

data/Post.kt

package com.example.skeleton.data

data class Post(
    val id: Int,
    val userId: Int,
    val title: String,
    val body: String
)

data/UserApi.kt (replace)

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Path

interface UserApi {
    @GET("users")
    suspend fun getUsers(): List<User>

    @GET("users/{id}/posts")
    suspend fun getPosts(@Path("id") userId: Int): List<Post>

    @GET("posts/{id}")
    suspend fun getPost(@Path("id") postId: Int): Post
}

data/UserRepository.kt (replace)

package com.example.skeleton.data

class UserRepository {
    private val api: UserApi = ApiClient
        .retrofit("https://jsonplaceholder.typicode.com/")
        .create(UserApi::class.java)

    suspend fun getUsers(): List<User> = api.getUsers()
    suspend fun getPosts(userId: Int): List<Post> = api.getPosts(userId)
    suspend fun getPost(postId: Int): Post = api.getPost(postId)
}

ui/users/UserDetailViewModel.kt

package com.example.skeleton.ui.users

// + VM imports

class UserDetailViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val userId: Int = checkNotNull(savedStateHandle["id"])   // from route "user/{id}"
    private val repository = UserRepository()

    private val _posts = MutableStateFlow<UiState<List<Post>>>(UiState.Loading)
    val posts: StateFlow<UiState<List<Post>>> = _posts.asStateFlow()

    init { load() }

    fun load() {
        _posts.value = UiState.Loading
        viewModelScope.launch {
            _posts.value = try {
                UiState.Success(repository.getPosts(userId))
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/users/PostDetailViewModel.kt

package com.example.skeleton.ui.users

// + VM imports

class PostDetailViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val postId: Int = checkNotNull(savedStateHandle["postId"])  // from route "post/{postId}"
    private val repository = UserRepository()

    private val _post = MutableStateFlow<UiState<Post>>(UiState.Loading)
    val post: StateFlow<UiState<Post>> = _post.asStateFlow()

    init { load() }

    fun load() {
        _post.value = UiState.Loading
        viewModelScope.launch {
            _post.value = try {
                UiState.Success(repository.getPost(postId))
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/users/UserDetailScreen.kt

package com.example.skeleton.ui.users

// + UI imports

@Composable
fun UserDetailScreen(
    userId: Int,
    listViewModel: UserListViewModel,          // the Activity-scoped one: list is already loaded
    onBack: () -> Unit,
    onPostClick: (Int) -> Unit,
    viewModel: UserDetailViewModel = viewModel()
) {
    val listState by listViewModel.state.collectAsStateWithLifecycle()
    val user = when (val s = listState) {
        is UiState.Success -> s.data.find { it.id == userId }
        else -> null
    }
    val posts by viewModel.posts.collectAsStateWithLifecycle()

    AppScaffold(title = user?.name ?: "Profile", onBack = onBack) { modifier ->
        LazyColumn(modifier.fillMaxSize()) {
            if (user != null) {
                item {
                    Column(Modifier.padding(16.dp)) {
                        Text(user.email)
                        Text("Phone: ${user.phone}")
                        Text("Website: ${user.website}")
                        Text("City: ${user.address.city}")
                    }
                    HorizontalDivider()
                }
            }
            item {
                Text(
                    "Posts",
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(16.dp)
                )
            }
            when (val s = posts) {
                UiState.Loading -> item { LoadingView(Modifier.height(120.dp)) }
                is UiState.Error -> item { ErrorView(s.message, viewModel::load, Modifier.height(160.dp)) }
                is UiState.Success -> items(s.data, key = { it.id }) { post ->
                    Text(
                        post.title,
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onPostClick(post.id) }
                            .padding(16.dp)
                    )
                    HorizontalDivider()
                }
            }
        }
    }
}

ui/users/PostDetailScreen.kt

package com.example.skeleton.ui.users

// + UI imports

@Composable
fun PostDetailScreen(onBack: () -> Unit, viewModel: PostDetailViewModel = viewModel()) {
    val state by viewModel.post.collectAsStateWithLifecycle()

    AppScaffold(title = "Post", onBack = onBack) { modifier ->
        when (val s = state) {
            UiState.Loading -> LoadingView(modifier)
            is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
            is UiState.Success -> Column(
                modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp)
            ) {
                Text(s.data.title, style = MaterialTheme.typography.titleLarge)
                Spacer(Modifier.height(12.dp))
                Text(s.data.body)
            }
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.users.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                val nav = rememberNavController()
                val listViewModel: UserListViewModel = viewModel()   // Activity-scoped, shared

                NavHost(navController = nav, startDestination = "users") {
                    composable("users") {
                        AppScaffold(title = "Users") { modifier ->
                            UserListScreen(
                                onUserClick = { id -> nav.navigate("user/$id") },
                                modifier = modifier,
                                viewModel = listViewModel
                            )
                        }
                    }
                    composable(
                        route = "user/{id}",
                        arguments = listOf(navArgument("id") { type = NavType.IntType })
                    ) { entry ->
                        UserDetailScreen(
                            userId = entry.arguments?.getInt("id") ?: 0,
                            listViewModel = listViewModel,
                            onBack = { nav.popBackStack() },
                            onPostClick = { postId -> nav.navigate("post/$postId") }
                        )
                    }
                    composable(
                        route = "post/{postId}",
                        arguments = listOf(navArgument("postId") { type = NavType.IntType })
                    ) {
                        PostDetailScreen(onBack = { nav.popBackStack() })
                    }
                }
            }
        }
    }
}

Why pass the id: it's small, safe in a route, and the detail screen can look up or refetch.

3B Pokédex: wrapped list, fetch by name (30 min)

APIs: https://pokeapi.co/api/v2/pokemon?limit=151 and /pokemon/{name}. List is wrapped in results. Extension: number on each row parsed from the URL.

data/Pokemon.kt

package com.example.skeleton.data

import com.google.gson.annotations.SerializedName

data class PokemonListResponse(val results: List<PokemonEntry>)

data class PokemonEntry(val name: String, val url: String) {
    // ".../pokemon/25/" → 25   (computed, no backing field, so Gson ignores it)
    val number: Int
        get() = url.trimEnd('/').substringAfterLast('/').toIntOrNull() ?: 0
}

data class PokemonDetail(
    val name: String,
    val height: Int,          // decimetres
    val weight: Int,          // hectograms
    val sprites: Sprites,
    val types: List<TypeSlot>
)

data class Sprites(@SerializedName("front_default") val frontDefault: String?)

data class TypeSlot(val type: NamedRef)

data class NamedRef(val name: String)

data/PokeApi.kt

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

interface PokeApi {
    @GET("pokemon")
    suspend fun getList(@Query("limit") limit: Int = 151): PokemonListResponse

    @GET("pokemon/{name}")
    suspend fun getPokemon(@Path("name") name: String): PokemonDetail
}

data/PokemonRepository.kt

package com.example.skeleton.data

class PokemonRepository {
    private val api: PokeApi = ApiClient
        .retrofit("https://pokeapi.co/api/v2/")
        .create(PokeApi::class.java)

    suspend fun getList(): List<PokemonEntry> = api.getList().results
    suspend fun getPokemon(name: String): PokemonDetail = api.getPokemon(name)
}

ui/pokedex/PokedexViewModels.kt

package com.example.skeleton.ui.pokedex

// + VM imports

class PokemonListViewModel : ViewModel() {
    private val repository = PokemonRepository()

    private val _state = MutableStateFlow<UiState<List<PokemonEntry>>>(UiState.Loading)
    val state: StateFlow<UiState<List<PokemonEntry>>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getList())
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

class PokemonDetailViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val name: String = checkNotNull(savedStateHandle["name"])   // route "pokemon/{name}"
    private val repository = PokemonRepository()

    private val _state = MutableStateFlow<UiState<PokemonDetail>>(UiState.Loading)
    val state: StateFlow<UiState<PokemonDetail>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getPokemon(name))
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/pokedex/PokedexScreens.kt

package com.example.skeleton.ui.pokedex

// + UI imports

private fun String.capitalized() = replaceFirstChar { it.uppercase() }

@Composable
fun PokemonListScreen(
    onPokemonClick: (String) -> Unit,
    modifier: Modifier = Modifier,
    viewModel: PokemonListViewModel = viewModel()
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val s = state) {
        UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
        is UiState.Success -> LazyColumn(modifier.fillMaxSize()) {
            items(s.data, key = { it.name }) { entry ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onPokemonClick(entry.name) }
                        .padding(horizontal = 16.dp, vertical = 14.dp)
                ) {
                    Text("#${entry.number}", modifier = Modifier.width(56.dp))   // extension
                    Text(entry.name.capitalized(), fontWeight = FontWeight.Bold)
                }
                HorizontalDivider()
            }
        }
    }
}

@Composable
fun PokemonDetailScreen(onBack: () -> Unit, viewModel: PokemonDetailViewModel = viewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    AppScaffold(title = "Pokémon", onBack = onBack) { modifier ->
        when (val s = state) {
            UiState.Loading -> LoadingView(modifier)
            is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
            is UiState.Success -> {
                val p = s.data
                Column(
                    modifier = modifier.fillMaxSize().padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    AsyncImage(
                        model = p.sprites.frontDefault,
                        contentDescription = p.name,
                        modifier = Modifier.size(200.dp)
                    )
                    Text(p.name.capitalized(), style = MaterialTheme.typography.headlineMedium)
                    Spacer(Modifier.height(8.dp))
                    Text("Types: " + p.types.joinToString { it.type.name.capitalized() })
                    Text("Height: ${p.height / 10.0} m")
                    Text("Weight: ${p.weight / 10.0} kg")
                }
            }
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.pokedex.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                val nav = rememberNavController()
                NavHost(navController = nav, startDestination = "list") {
                    composable("list") {
                        AppScaffold(title = "Pokédex") { modifier ->
                            PokemonListScreen(
                                onPokemonClick = { name -> nav.navigate("pokemon/$name") },
                                modifier = modifier
                            )
                        }
                    }
                    composable(
                        route = "pokemon/{name}",
                        arguments = listOf(navArgument("name") { type = NavType.StringType })
                    ) {
                        PokemonDetailScreen(onBack = { nav.popBackStack() })
                    }
                }
            }
        }
    }
}
4A–4G All extensions on the 2B crypto app (~10 min each)

Uses Ticker, TickerRepository and TickerRow from 2B. One ViewModel with search (4A), sort (4B), retry (4C), pull-to-refresh (4D), auto-refresh every 30 s (4E), favorites pinned to top (4F), and empty-search message (4G).

ui/tickers/MarketViewModel.kt

package com.example.skeleton.ui.tickers

// + VM imports
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

enum class SortOrder(val label: String) { RANK("Rank"), PRICE("Price"), CHANGE("24h") }

class MarketViewModel : ViewModel() {
    private val repository = TickerRepository()

    private val _state = MutableStateFlow<UiState<List<Ticker>>>(UiState.Loading)   // raw data
    private val _query = MutableStateFlow("")
    private val _sort = MutableStateFlow(SortOrder.RANK)
    private val _favs = MutableStateFlow<Set<String>>(emptySet())
    private val _refreshing = MutableStateFlow(false)
    private val _updatedAt = MutableStateFlow("")

    val query: StateFlow<String> = _query.asStateFlow()
    val sort: StateFlow<SortOrder> = _sort.asStateFlow()
    val favs: StateFlow<Set<String>> = _favs.asStateFlow()
    val refreshing: StateFlow<Boolean> = _refreshing.asStateFlow()
    val updatedAt: StateFlow<String> = _updatedAt.asStateFlow()

    // What the screen shows = raw data + search + sort + favorites
    val visible: StateFlow<UiState<List<Ticker>>> =
        combine(_state, _query, _sort, _favs) { state, q, sort, favs ->
            if (state !is UiState.Success) {
                state
            } else {
                val filtered = state.data.filter {
                    q.isBlank() || it.name.contains(q, ignoreCase = true) ||
                        it.symbol.contains(q, ignoreCase = true)
                }
                val sorted = when (sort) {
                    SortOrder.RANK -> filtered.sortedBy { it.rank }
                    SortOrder.PRICE -> filtered.sortedByDescending { it.quotes.usd.price }
                    SortOrder.CHANGE -> filtered.sortedByDescending { it.quotes.usd.change24h ?: 0.0 }
                }
                UiState.Success(sorted.sortedByDescending { it.id in favs })   // favorites first
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)

    init {
        viewModelScope.launch {                     // 4E: auto-refresh
            while (isActive) {
                fetch()
                delay(30_000)
            }
        }
    }

    fun onQueryChange(q: String) { _query.value = q }
    fun onSortChange(s: SortOrder) { _sort.value = s }
    fun toggleFavorite(id: String) = _favs.update { if (id in it) it - id else it + id }

    fun retry() {                                   // 4C
        _state.value = UiState.Loading
        viewModelScope.launch { fetch() }
    }

    fun refresh() {                                 // 4D: keep the old list visible
        viewModelScope.launch {
            _refreshing.value = true
            fetch()
            _refreshing.value = false
        }
    }

    private suspend fun fetch() {
        try {
            _state.value = UiState.Success(repository.getTop50())
            _updatedAt.value = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
        } catch (e: Exception) {
            // Only show the error screen if there is nothing to show yet
            if (_state.value !is UiState.Success) _state.value = UiState.Error(e.toMessage())
        }
    }
}

ui/tickers/MarketScreen.kt

package com.example.skeleton.ui.tickers

// + UI imports
import androidx.compose.material3.pulltorefresh.PullToRefreshBox

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MarketScreen(modifier: Modifier = Modifier, viewModel: MarketViewModel = viewModel()) {
    val state by viewModel.visible.collectAsStateWithLifecycle()
    val query by viewModel.query.collectAsStateWithLifecycle()
    val sort by viewModel.sort.collectAsStateWithLifecycle()
    val favs by viewModel.favs.collectAsStateWithLifecycle()
    val refreshing by viewModel.refreshing.collectAsStateWithLifecycle()
    val updatedAt by viewModel.updatedAt.collectAsStateWithLifecycle()

    Column(modifier.fillMaxSize()) {
        OutlinedTextField(                                        // 4A
            value = query,
            onValueChange = viewModel::onQueryChange,
            label = { Text("Search name or symbol") },
            leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
            singleLine = true,
            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)
        )
        Row(                                                      // 4B
            modifier = Modifier.padding(horizontal = 16.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            SortOrder.entries.forEach { option ->
                FilterChip(
                    selected = sort == option,
                    onClick = { viewModel.onSortChange(option) },
                    label = { Text(option.label) }
                )
            }
        }
        if (updatedAt.isNotEmpty()) {
            Text(
                "Updated $updatedAt",
                style = MaterialTheme.typography.labelMedium,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
            )
        }
        PullToRefreshBox(                                         // 4D
            isRefreshing = refreshing,
            onRefresh = viewModel::refresh,
            modifier = Modifier.weight(1f)
        ) {
            when (val s = state) {
                UiState.Loading -> LoadingView()
                is UiState.Error -> ErrorView(s.message, viewModel::retry)        // 4C
                is UiState.Success ->
                    if (s.data.isEmpty()) {
                        EmptyView("No coins match \"$query\"")                   // 4G
                    } else {
                        LazyColumn(Modifier.fillMaxSize()) {
                            items(s.data, key = { it.id }) { ticker ->
                                Row(verticalAlignment = Alignment.CenterVertically) {
                                    TickerRow(ticker, Modifier.weight(1f))
                                    IconButton(onClick = { viewModel.toggleFavorite(ticker.id) }) {   // 4F
                                        Icon(
                                            if (ticker.id in favs) Icons.Filled.Star else Icons.Filled.StarBorder,
                                            contentDescription = "Favorite"
                                        )
                                    }
                                }
                                HorizontalDivider()
                            }
                        }
                    }
            }
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.tickers.MarketScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                AppScaffold(title = "Markets") { modifier ->
                    MarketScreen(modifier = modifier)
                }
            }
        }
    }
}

Talk track: "I keep the fetched data untouched and derive the visible list with combine, so search, sort, favorites and refresh don't fight each other."

5A Live ticker: 20 prices every second, pause/resume, price alerts (35 min)

No network. Tap a row to set a target price; a Snackbar fires once when the price crosses it.

ui/live/LiveTickerViewModel.kt

package com.example.skeleton.ui.live

// + VM imports
import com.example.skeleton.ui.formatPrice
import kotlin.random.Random

data class Quote(val symbol: String, val price: Double, val previous: Double)

class LiveTickerViewModel : ViewModel() {
    private val _quotes = MutableStateFlow(
        listOf(
            "AAPL", "AMZN", "GOOGL", "HOOD", "META", "MSFT", "NFLX", "NVDA", "TSLA", "AMD",
            "COIN", "PLTR", "SHOP", "UBER", "ABNB", "SNOW", "PYPL", "INTC", "ORCL", "DIS"
        ).map { symbol ->
            val start = Random.nextDouble(20.0, 500.0)
            Quote(symbol, start, start)
        }
    )
    val quotes: StateFlow<List<Quote>> = _quotes.asStateFlow()

    private val _running = MutableStateFlow(false)
    val running: StateFlow<Boolean> = _running.asStateFlow()

    private val _targets = MutableStateFlow<Map<String, Double>>(emptyMap())
    val targets: StateFlow<Map<String, Double>> = _targets.asStateFlow()

    // One-off messages for the Snackbar. Buffer so the ticking loop never waits on the UI.
    private val _alerts = MutableSharedFlow<String>(extraBufferCapacity = 16)
    val alerts: SharedFlow<String> = _alerts.asSharedFlow()

    private var job: Job? = null

    init { start() }

    fun start() {
        if (job?.isActive == true) return          // never two loops
        _running.value = true
        job = viewModelScope.launch {
            while (isActive) {
                delay(1_000)
                _quotes.update { list ->
                    list.map { q ->
                        q.copy(
                            previous = q.price,
                            price = q.price * (1 + Random.nextDouble(-0.01, 0.01))
                        )
                    }
                }
                checkAlerts()
            }
        }
    }

    fun pause() {
        job?.cancel()
        _running.value = false
    }

    fun setTarget(symbol: String, target: Double) {
        _targets.update { it + (symbol to target) }
    }

    private fun checkAlerts() {
        for (q in _quotes.value) {
            val target = _targets.value[q.symbol] ?: continue
            val crossedUp = q.previous < target && q.price >= target
            val crossedDown = q.previous > target && q.price <= target
            if (crossedUp || crossedDown) {
                _targets.update { it - q.symbol }      // fire once
                _alerts.tryEmit("${q.symbol} crossed ${formatPrice(target)}")
            }
        }
    }
}

ui/live/LiveTickerScreen.kt

package com.example.skeleton.ui.live

// + UI imports
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.KeyboardType

@Composable
fun LiveTickerScreen(viewModel: LiveTickerViewModel = viewModel()) {
    val quotes by viewModel.quotes.collectAsStateWithLifecycle()
    val running by viewModel.running.collectAsStateWithLifecycle()
    val targets by viewModel.targets.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    var alertSymbol by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(Unit) {
        viewModel.alerts.collect { snackbarHostState.showSnackbar(it) }
    }

    AppScaffold(
        title = "Live prices",
        snackbarHostState = snackbarHostState,
        floatingActionButton = {
            ExtendedFloatingActionButton(
                onClick = { if (running) viewModel.pause() else viewModel.start() }
            ) {
                Text(if (running) "Pause" else "Resume")
            }
        }
    ) { modifier ->
        LazyColumn(modifier.fillMaxSize()) {
            items(quotes, key = { it.symbol }) { q ->        // stable keys → no flicker
                QuoteRow(
                    q = q,
                    target = targets[q.symbol],
                    modifier = Modifier.clickable { alertSymbol = q.symbol }
                )
                HorizontalDivider()
            }
        }
    }

    alertSymbol?.let { symbol ->
        TargetDialog(
            symbol = symbol,
            onDismiss = { alertSymbol = null },
            onConfirm = { target ->
                viewModel.setTarget(symbol, target)
                alertSymbol = null
            }
        )
    }
}

@Composable
fun QuoteRow(q: Quote, target: Double?, modifier: Modifier = Modifier) {
    val color = when {
        q.price > q.previous -> GainGreen
        q.price < q.previous -> Color.Red
        else -> MaterialTheme.colorScheme.onSurface
    }
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            Text(q.symbol, fontWeight = FontWeight.Bold)
            if (target != null) {
                Text("Alert at ${formatPrice(target)}", style = MaterialTheme.typography.bodySmall)
            }
        }
        Spacer(Modifier.weight(1f))
        Text(formatPrice(q.price), color = color, fontWeight = FontWeight.Bold)
    }
}

@Composable
fun TargetDialog(symbol: String, onDismiss: () -> Unit, onConfirm: (Double) -> Unit) {
    var text by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Price alert for $symbol") },
        text = {
            OutlinedTextField(
                value = text,
                onValueChange = { text = it },
                label = { Text("Target price") },
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
            )
        },
        confirmButton = {
            TextButton(onClick = { text.toDoubleOrNull()?.let(onConfirm) }) { Text("Set") }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text("Cancel") }
        }
    )
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.live.LiveTickerScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                LiveTickerScreen()
            }
        }
    }
}

Probed: state in the ViewModel, stable keys, the loop cancelled on pause and never started twice, rotation keeps prices.

5B Countdown timers (25 min)

A button adds a 30-second timer. Each counts down on its own, can pause/resume, shows Done, and can be removed.

ui/timers/TimersViewModel.kt

package com.example.skeleton.ui.timers

// + VM imports

data class CountdownTimer(val id: Int, val remaining: Int, val running: Boolean = true)

class TimersViewModel : ViewModel() {
    private var nextId = 1

    private val _timers = MutableStateFlow<List<CountdownTimer>>(emptyList())
    val timers: StateFlow<List<CountdownTimer>> = _timers.asStateFlow()

    init {
        viewModelScope.launch {                    // ONE loop ticks every running timer
            while (isActive) {
                delay(1_000)
                _timers.update { list ->
                    list.map {
                        if (it.running && it.remaining > 0) it.copy(remaining = it.remaining - 1) else it
                    }
                }
            }
        }
    }

    fun add() = _timers.update { it + CountdownTimer(id = nextId++, remaining = 30) }

    fun remove(id: Int) = _timers.update { list -> list.filterNot { it.id == id } }

    fun toggle(id: Int) = _timers.update { list ->
        list.map { if (it.id == id) it.copy(running = !it.running) else it }
    }
}

ui/timers/TimersScreen.kt

package com.example.skeleton.ui.timers

// + UI imports

@Composable
fun TimersScreen(viewModel: TimersViewModel = viewModel()) {
    val timers by viewModel.timers.collectAsStateWithLifecycle()

    AppScaffold(
        title = "Timers",
        floatingActionButton = {
            FloatingActionButton(onClick = viewModel::add) {
                Icon(Icons.Filled.Add, contentDescription = "Add timer")
            }
        }
    ) { modifier ->
        if (timers.isEmpty()) {
            EmptyView("Tap + to add a 30-second timer", modifier)
        } else {
            LazyColumn(modifier.fillMaxSize()) {
                items(timers, key = { it.id }) { t ->
                    TimerRow(
                        timer = t,
                        onToggle = { viewModel.toggle(t.id) },
                        onRemove = { viewModel.remove(t.id) }
                    )
                    HorizontalDivider()
                }
            }
        }
    }
}

@Composable
fun TimerRow(timer: CountdownTimer, onToggle: () -> Unit, onRemove: () -> Unit) {
    val done = timer.remaining == 0
    Row(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text("Timer ${timer.id}", fontWeight = FontWeight.Bold)
        Spacer(Modifier.weight(1f))
        Text(
            if (done) "Done" else "${timer.remaining}s",
            color = if (done) GainGreen else MaterialTheme.colorScheme.onSurface
        )
        if (!done) {
            TextButton(onClick = onToggle) { Text(if (timer.running) "Pause" else "Resume") }
        }
        IconButton(onClick = onRemove) {
            Icon(Icons.Filled.Close, contentDescription = "Remove")
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.timers.TimersScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                TimersScreen()
            }
        }
    }
}

Named CountdownTimer, not Timer, to avoid clashing with java.util.Timer.

6A Mock: crypto asset browser (60 min)

Uses Ticker.kt, PaprikaApi.kt, TickerRepository.kt and TickerRow (in TickerListScreen.kt) from 2B. List with search → tap → detail (rank, price, 24h change, market cap). Surprise: refresh every 15 s without losing the search.

ui/tickers/AssetViewModels.kt

package com.example.skeleton.ui.tickers

// + VM imports

class AssetListViewModel : ViewModel() {
    private val repository = TickerRepository()

    private val _state = MutableStateFlow<UiState<List<Ticker>>>(UiState.Loading)
    private val _query = MutableStateFlow("")
    val query: StateFlow<String> = _query.asStateFlow()

    val visible: StateFlow<UiState<List<Ticker>>> =
        combine(_state, _query) { state, q ->
            if (state is UiState.Success && q.isNotBlank()) {
                UiState.Success(state.data.filter {
                    it.name.contains(q, ignoreCase = true) || it.symbol.contains(q, ignoreCase = true)
                })
            } else {
                state
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)

    init {
        viewModelScope.launch {                    // surprise: refresh every 15 s; query stays applied
            while (isActive) {
                fetch()
                delay(15_000)
            }
        }
    }

    fun onQueryChange(q: String) { _query.value = q }

    fun retry() {
        _state.value = UiState.Loading
        viewModelScope.launch { fetch() }
    }

    private suspend fun fetch() {
        try {
            _state.value = UiState.Success(repository.getTop50())
        } catch (e: Exception) {
            if (_state.value !is UiState.Success) _state.value = UiState.Error(e.toMessage())
        }
    }
}

class AssetDetailViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val id: String = checkNotNull(savedStateHandle["id"])      // route "asset/{id}"
    private val repository = TickerRepository()

    private val _state = MutableStateFlow<UiState<Ticker>>(UiState.Loading)
    val state: StateFlow<UiState<Ticker>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getTicker(id))
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/tickers/AssetScreens.kt

package com.example.skeleton.ui.tickers

// + UI imports

@Composable
fun AssetListScreen(
    onAssetClick: (String) -> Unit,
    modifier: Modifier = Modifier,
    viewModel: AssetListViewModel = viewModel()
) {
    val state by viewModel.visible.collectAsStateWithLifecycle()
    val query by viewModel.query.collectAsStateWithLifecycle()

    Column(modifier.fillMaxSize()) {
        OutlinedTextField(
            value = query,
            onValueChange = viewModel::onQueryChange,
            label = { Text("Search") },
            leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
            singleLine = true,
            modifier = Modifier.fillMaxWidth().padding(16.dp)
        )
        when (val s = state) {
            UiState.Loading -> LoadingView()
            is UiState.Error -> ErrorView(s.message, viewModel::retry)
            is UiState.Success ->
                if (s.data.isEmpty()) {
                    EmptyView("No assets match \"$query\"")
                } else {
                    LazyColumn(Modifier.fillMaxSize()) {
                        items(s.data, key = { it.id }) { ticker ->
                            TickerRow(ticker, Modifier.clickable { onAssetClick(ticker.id) })
                            HorizontalDivider()
                        }
                    }
                }
        }
    }
}

@Composable
fun AssetDetailScreen(onBack: () -> Unit, viewModel: AssetDetailViewModel = viewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    AppScaffold(title = "Asset", onBack = onBack) { modifier ->
        when (val s = state) {
            UiState.Loading -> LoadingView(modifier)
            is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
            is UiState.Success -> {
                val t = s.data
                Column(modifier.fillMaxSize().padding(16.dp)) {
                    Text("${t.name} (${t.symbol})", style = MaterialTheme.typography.headlineSmall)
                    Spacer(Modifier.height(16.dp))
                    DetailLine("Rank", "#${t.rank}")
                    DetailLine("Price", formatPrice(t.quotes.usd.price))
                    Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
                        Text("24h change")
                        Spacer(Modifier.weight(1f))
                        ChangeText(t.quotes.usd.change24h)
                    }
                    DetailLine("Market cap", t.quotes.usd.marketCap?.let { formatPrice(it) } ?: "—")
                }
            }
        }
    }
}

@Composable
private fun DetailLine(label: String, value: String) {
    Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
        Text(label)
        Spacer(Modifier.weight(1f))
        Text(value, fontWeight = FontWeight.Bold)
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.tickers.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                val nav = rememberNavController()
                NavHost(navController = nav, startDestination = "assets") {
                    composable("assets") {
                        AppScaffold(title = "Crypto") { modifier ->
                            AssetListScreen(
                                onAssetClick = { id -> nav.navigate("asset/$id") },
                                modifier = modifier
                            )
                        }
                    }
                    composable(
                        route = "asset/{id}",
                        arguments = listOf(navArgument("id") { type = NavType.StringType })
                    ) {
                        AssetDetailScreen(onBack = { nav.popBackStack() })
                    }
                }
            }
        }
    }
}

Follow-ups: "Why the id?" (small, survives process death, detail can refetch fresh data). "10,000 assets?" (paging, server-side search, stable keys).

6B Mock: posts + comments, spoken spec (60 min)

APIs: https://jsonplaceholder.typicode.com/posts, /posts/{id}, /posts/{id}/comments. Feed with title + 2-line preview → tap → full post + comments. Surprise: read posts appear dimmed.

data/Posts.kt

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Path

data class Post(val id: Int, val userId: Int, val title: String, val body: String)

data class Comment(val id: Int, val name: String, val email: String, val body: String)

interface PostApi {
    @GET("posts")
    suspend fun getPosts(): List<Post>

    @GET("posts/{id}")
    suspend fun getPost(@Path("id") id: Int): Post

    @GET("posts/{id}/comments")
    suspend fun getComments(@Path("id") id: Int): List<Comment>
}

class PostRepository {
    private val api: PostApi = ApiClient
        .retrofit("https://jsonplaceholder.typicode.com/")
        .create(PostApi::class.java)

    suspend fun getPosts(): List<Post> = api.getPosts()
    suspend fun getPost(id: Int): Post = api.getPost(id)
    suspend fun getComments(id: Int): List<Comment> = api.getComments(id)
}

ui/feed/FeedViewModels.kt

package com.example.skeleton.ui.feed

// + VM imports

class FeedViewModel : ViewModel() {
    private val repository = PostRepository()

    private val _state = MutableStateFlow<UiState<List<Post>>>(UiState.Loading)
    val state: StateFlow<UiState<List<Post>>> = _state.asStateFlow()

    private val _readIds = MutableStateFlow<Set<Int>>(emptySet())      // surprise extension
    val readIds: StateFlow<Set<Int>> = _readIds.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getPosts())
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }

    fun markRead(id: Int) = _readIds.update { it + id }
}

data class PostWithComments(val post: Post, val comments: List<Comment>)

class PostViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val id: Int = checkNotNull(savedStateHandle["id"])          // route "post/{id}"
    private val repository = PostRepository()

    private val _state = MutableStateFlow<UiState<PostWithComments>>(UiState.Loading)
    val state: StateFlow<UiState<PostWithComments>> = _state.asStateFlow()

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                // Both requests at the same time. coroutineScope makes a failure
                // land in this catch instead of crashing the app.
                coroutineScope {
                    val post = async { repository.getPost(id) }
                    val comments = async { repository.getComments(id) }
                    UiState.Success(PostWithComments(post.await(), comments.await()))
                }
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }
}

ui/feed/FeedScreens.kt

package com.example.skeleton.ui.feed

// + UI imports
import androidx.compose.ui.draw.alpha

@Composable
fun FeedScreen(
    viewModel: FeedViewModel,
    onPostClick: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val readIds by viewModel.readIds.collectAsStateWithLifecycle()

    when (val s = state) {
        UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
        is UiState.Success -> LazyColumn(modifier.fillMaxSize()) {
            items(s.data, key = { it.id }) { post ->
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { onPostClick(post.id) }
                        .alpha(if (post.id in readIds) 0.5f else 1f)      // read = dimmed
                        .padding(16.dp)
                ) {
                    Text(post.title, fontWeight = FontWeight.Bold)
                    Text(
                        post.body,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                HorizontalDivider()
            }
        }
    }
}

@Composable
fun PostScreen(onBack: () -> Unit, viewModel: PostViewModel = viewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    AppScaffold(title = "Post", onBack = onBack) { modifier ->
        when (val s = state) {
            UiState.Loading -> LoadingView(modifier)
            is UiState.Error -> ErrorView(s.message, viewModel::load, modifier)
            is UiState.Success -> LazyColumn(modifier.fillMaxSize()) {
                item {
                    Column(Modifier.padding(16.dp)) {
                        Text(s.data.post.title, style = MaterialTheme.typography.titleLarge)
                        Spacer(Modifier.height(8.dp))
                        Text(s.data.post.body)
                        Spacer(Modifier.height(16.dp))
                        Text(
                            "Comments (${s.data.comments.size})",
                            style = MaterialTheme.typography.titleMedium
                        )
                    }
                    HorizontalDivider()
                }
                items(s.data.comments, key = { it.id }) { c ->
                    Column(Modifier.fillMaxWidth().padding(16.dp)) {
                        Text(c.name, fontWeight = FontWeight.Bold)
                        Text(c.email, style = MaterialTheme.typography.bodySmall)
                        Spacer(Modifier.height(4.dp))
                        Text(c.body)
                    }
                    HorizontalDivider()
                }
            }
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.feed.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                val nav = rememberNavController()
                val feedViewModel: FeedViewModel = viewModel()     // Activity-scoped: keeps read state

                NavHost(navController = nav, startDestination = "feed") {
                    composable("feed") {
                        AppScaffold(title = "Feed") { modifier ->
                            FeedScreen(
                                viewModel = feedViewModel,
                                onPostClick = { id ->
                                    feedViewModel.markRead(id)
                                    nav.navigate("post/$id")
                                },
                                modifier = modifier
                            )
                        }
                    }
                    composable(
                        route = "post/{id}",
                        arguments = listOf(navArgument("id") { type = NavType.IntType })
                    ) {
                        PostScreen(onBack = { nav.popBackStack() })
                    }
                }
            }
        }
    }
}

"Keep read state across restarts?" → SharedPreferences/DataStore (Extras page) or Room.

6C Mock: unfamiliar API — REST Countries (60 min)

API: https://restcountries.com/v3.1/all?fields=name,flags,region,population,capital,cca3 (fields is required). List with flag, name, region; filter by region; tap → capital and population. Surprise: sort by population, formatted as 1.2M.

data/Country.kt

package com.example.skeleton.data

import retrofit2.http.GET
import retrofit2.http.Query

data class Country(
    val name: CountryName,
    val flags: Flags,
    val region: String,
    val population: Long,
    val capital: List<String>?,      // array, sometimes empty or missing
    val cca3: String                 // unique 3-letter code → list key + route id
)

data class CountryName(val common: String)

data class Flags(val png: String)

interface CountryApi {
    @GET("v3.1/all")
    suspend fun getAll(
        @Query("fields") fields: String = "name,flags,region,population,capital,cca3"
    ): List<Country>
}

class CountryRepository {
    private val api: CountryApi = ApiClient
        .retrofit("https://restcountries.com/")
        .create(CountryApi::class.java)

    suspend fun getCountries(): List<Country> = api.getAll()
}

ui/countries/CountryListViewModel.kt

package com.example.skeleton.ui.countries

// + VM imports

class CountryListViewModel : ViewModel() {
    private val repository = CountryRepository()

    private val _state = MutableStateFlow<UiState<List<Country>>>(UiState.Loading)
    val state: StateFlow<UiState<List<Country>>> = _state.asStateFlow()

    private val _region = MutableStateFlow<String?>(null)          // null = all regions
    val region: StateFlow<String?> = _region.asStateFlow()

    private val _sortByPopulation = MutableStateFlow(false)
    val sortByPopulation: StateFlow<Boolean> = _sortByPopulation.asStateFlow()

    val regions: StateFlow<List<String>> = _state.map { s ->
        if (s is UiState.Success) s.data.map { it.region }.distinct().sorted() else emptyList()
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val visible: StateFlow<UiState<List<Country>>> =
        combine(_state, _region, _sortByPopulation) { state, region, byPopulation ->
            if (state !is UiState.Success) {
                state
            } else {
                val filtered = state.data.filter { region == null || it.region == region }
                UiState.Success(
                    if (byPopulation) filtered.sortedByDescending { it.population }
                    else filtered.sortedBy { it.name.common }
                )
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = try {
                UiState.Success(repository.getCountries())
            } catch (e: Exception) {
                UiState.Error(e.toMessage())
            }
        }
    }

    fun onRegionClick(r: String) { _region.value = if (_region.value == r) null else r }

    fun toggleSort() = _sortByPopulation.update { !it }

    fun find(cca3: String): Country? = when (val s = _state.value) {
        is UiState.Success -> s.data.find { it.cca3 == cca3 }
        else -> null
    }
}

ui/countries/CountryScreens.kt

package com.example.skeleton.ui.countries

// + UI imports

fun formatPopulation(n: Long): String = when {
    n >= 1_000_000_000 -> "%.1fB".format(n / 1e9)
    n >= 1_000_000 -> "%.1fM".format(n / 1e6)
    n >= 1_000 -> "%.1fK".format(n / 1e3)
    else -> n.toString()
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CountryListScreen(
    viewModel: CountryListViewModel,
    onCountryClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val state by viewModel.visible.collectAsStateWithLifecycle()
    val regions by viewModel.regions.collectAsStateWithLifecycle()
    val region by viewModel.region.collectAsStateWithLifecycle()
    val byPopulation by viewModel.sortByPopulation.collectAsStateWithLifecycle()

    Column(modifier.fillMaxSize()) {
        LazyRow(
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            item {
                FilterChip(
                    selected = byPopulation,
                    onClick = viewModel::toggleSort,
                    label = { Text("Largest first") }
                )
            }
            items(regions) { r ->
                FilterChip(
                    selected = region == r,
                    onClick = { viewModel.onRegionClick(r) },
                    label = { Text(r) }
                )
            }
        }
        when (val s = state) {
            UiState.Loading -> LoadingView()
            is UiState.Error -> ErrorView(s.message, viewModel::load)
            is UiState.Success -> LazyColumn(Modifier.fillMaxSize()) {
                items(s.data, key = { it.cca3 }) { c ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onCountryClick(c.cca3) }
                            .padding(horizontal = 16.dp, vertical = 10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        AsyncImage(
                            model = c.flags.png,
                            contentDescription = "${c.name.common} flag",
                            modifier = Modifier.size(width = 40.dp, height = 28.dp)
                        )
                        Spacer(Modifier.width(12.dp))
                        Column {
                            Text(c.name.common, fontWeight = FontWeight.Bold)
                            Text(c.region, style = MaterialTheme.typography.bodySmall)
                        }
                        Spacer(Modifier.weight(1f))
                        Text(formatPopulation(c.population))
                    }
                    HorizontalDivider()
                }
            }
        }
    }
}

@Composable
fun CountryDetailScreen(country: Country?, onBack: () -> Unit) {
    AppScaffold(title = country?.name?.common ?: "Country", onBack = onBack) { modifier ->
        if (country == null) {
            EmptyView("Country not found", modifier)
        } else {
            Column(modifier.fillMaxSize().padding(16.dp)) {
                AsyncImage(
                    model = country.flags.png,
                    contentDescription = "${country.name.common} flag",
                    modifier = Modifier.fillMaxWidth().height(180.dp)
                )
                Spacer(Modifier.height(16.dp))
                Text("Capital: ${country.capital?.firstOrNull() ?: "None"}")
                Text("Population: " + "%,d".format(country.population))
                Text("Region: ${country.region}")
            }
        }
    }
}

MainActivity.kt

package com.example.skeleton

// + MainActivity imports
import com.example.skeleton.ui.countries.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            SkeletonTheme {
                val nav = rememberNavController()
                val listViewModel: CountryListViewModel = viewModel()   // Activity-scoped, shared

                NavHost(navController = nav, startDestination = "countries") {
                    composable("countries") {
                        AppScaffold(title = "Countries") { modifier ->
                            CountryListScreen(
                                viewModel = listViewModel,
                                onCountryClick = { code -> nav.navigate("country/$code") },
                                modifier = modifier
                            )
                        }
                    }
                    composable(
                        route = "country/{cca3}",
                        arguments = listOf(navArgument("cca3") { type = NavType.StringType })
                    ) { entry ->
                        val code = entry.arguments?.getString("cca3") ?: ""
                        CountryDetailScreen(
                            country = listViewModel.find(code),
                            onBack = { nav.popBackStack() }
                        )
                    }
                }
            }
        }
    }
}

Follow-ups: "What if capital is empty?" (firstOrNull() ?: "None"). "How would you test the filter?" (unit-test the ViewModel's visible with a fake repository).

Compose quick reference

NeedUse
Vertical / horizontal / layeredColumn / Row / Box
Push to far edgeSpacer(Modifier.weight(1f)) (only inside Row/Column)
GapSpacer(Modifier.width(12.dp)) or Arrangement.spacedBy(8.dp)
Center childrenRow: verticalAlignment = Alignment.CenterVertically · Column: horizontalAlignment = Alignment.CenterHorizontally · Box: contentAlignment = Alignment.Center
Scrolling listLazyColumn { items(list, key = { it.id }) { ... } } · single row: item { }
TapModifier.clickable { } (put it before padding so the padding is tappable)
Image from URLAsyncImage(model = url, contentDescription = name, modifier = Modifier.size(40.dp))
Text inputOutlinedTextField(value = q, onValueChange = onQ, label = { Text("Search") }, singleLine = true)
TruncateText(s, maxLines = 2, overflow = TextOverflow.Ellipsis)
LoadingCircularProgressIndicator()
Card rowCard(Modifier.fillMaxWidth().padding(8.dp)) { ... }
Local UI statevar x by remember { mutableStateOf(false) } · survives rotation: rememberSaveable
ViewModel stateval s by vm.state.collectAsStateWithLifecycle()
Run once / on key changeLaunchedEffect(key) { ... }
Theme valuesMaterialTheme.typography.bodySmall, MaterialTheme.colorScheme.primary
Experimental API error@OptIn(ExperimentalMaterial3Api::class) (TopAppBar, PullToRefreshBox)

Rules: UI = f(state). Composables return nothing and can only be called from composables. Data flows down; events flow up as lambdas. No fetching or list-building inside composables. Every composable takes modifier: Modifier = Modifier.

Kotlin quick reference

list.filter { it.price > 0 }          list.map { it.name }           list.find { it.id == id }
list.sortedBy { it.rank }             list.sortedByDescending { it.price }
list.take(50)                         list.distinct()                list.groupBy { it.region }
list.any { }  list.all { }  list.count { }  list.sumOf { it.price }  list.joinToString { it.name }
list.firstOrNull()                    list + item   set - item       list.filterNot { }

s.contains(q, ignoreCase = true)      s.replaceFirstChar { it.uppercase() }   s.uppercase()
s.substringAfterLast('/')             s.trimEnd('/')    s.toIntOrNull()       s.toDoubleOrNull()
"%.2f".format(x)                      "$" + "%.2f".format(price)              "%.1fM".format(n / 1e6)

a ?: b                // b if a is null
a?.b                  // null if a is null
x as? Type            // null if not that type
obj.copy(price = 1.0) // data class: new object, one field changed
when (val s = state) { is X -> ...; else -> ... }
viewModel::load       // function reference = { viewModel.load() }

Error → fix

You seeFix
Unresolved reference (Row, width, padding, getValue)Missing import. Use Alt+Enter and pick the androidx.compose one. Extension functions like width need their own import.
@Composable invocations can only happen from a @Composable functionA composable was called inside LazyColumn { } or onClick = { }. Wrap it in item { }, or change state instead.
Property delegate must have a getValue methodimport androidx.compose.runtime.getValue
This API is experimental@OptIn(ExperimentalMaterial3Api::class)
Smart cast impossible on statewhen (val s = state)
UnknownHostException / SecurityExceptionINTERNET permission missing. Add it and reinstall the app.
Cleartext HTTP traffic not permittedUse https, or android:usesCleartextTraffic="true"
baseUrl must end in /Add the trailing /
Expected BEGIN_ARRAY but was BEGIN_OBJECTThe JSON is wrapped. Add data class Resp(val results: List<T>)
Expected BEGIN_OBJECT but was BEGIN_ARRAYThe opposite: return List<T>
Field shows null or blankName mismatch. Use @SerializedName("json_name") and check Logcat.
NullPointerException on a model fieldJSON had null. Make the field nullable (?) and use ?: "—"
NetworkOnMainThreadExceptionMake the API function suspend and call it in viewModelScope.launch
Endless requests in LogcatLoading was called from the composable body. Move it to the ViewModel init.
List resets on rotationState was in remember or the Activity. Move it to the ViewModel.
Content under the status barPass Modifier.padding(innerPadding) to the content
Image blankMissing coil-network-okhttp, or the URL is null
LazyColumn crash: infinite heightDon't nest it inside Column(Modifier.verticalScroll())
Typing does nothing in a text fieldonValueChange must update the state that feeds value
UI doesn't update after a changeAn object was mutated in place. Use a val model + copy() and assign a new list.
Local server unreachable from the emulatorUse 10.0.2.2, not localhost
HTTP 429Rate limited. Catch HttpException, show a message, wait before retrying.

Extras

Grid instead of a list

import androidx.compose.foundation.lazy.grid.*      // LazyVerticalGrid, GridCells, items

LazyVerticalGrid(
    columns = GridCells.Fixed(2),                    // or GridCells.Adaptive(150.dp)
    modifier = modifier,
    contentPadding = PaddingValues(8.dp),
    horizontalArrangement = Arrangement.spacedBy(8.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp)
) {
    items(list, key = { it.id }) { item ->
        Card(Modifier.clickable { onClick(item.id) }) {
            Column(Modifier.padding(12.dp)) {
                AsyncImage(model = item.image, contentDescription = item.name, modifier = Modifier.size(64.dp))
                Text(item.name, fontWeight = FontWeight.Bold)
            }
        }
    }
}

Swipeable pages + tabs (Pager)

import androidx.compose.foundation.pager.*          // HorizontalPager, rememberPagerState

val titles = listOf("Stocks", "Crypto", "Watchlist")
val pagerState = rememberPagerState(pageCount = { titles.size })
val scope = rememberCoroutineScope()

Column(modifier.fillMaxSize()) {
    TabRow(selectedTabIndex = pagerState.currentPage) {
        titles.forEachIndexed { i, title ->
            Tab(
                selected = pagerState.currentPage == i,
                onClick = { scope.launch { pagerState.animateScrollToPage(i) } },
                text = { Text(title) }
            )
        }
    }
    HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->
        when (page) {
            0 -> StocksScreen()
            1 -> CryptoScreen()
            else -> WatchlistScreen()
        }
    }
}

Snackbar (messages, alerts)

val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()

Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { innerPadding ->
    Button(onClick = { scope.launch { snackbarHostState.showSnackbar("Saved") } }) { Text("Save") }
}

// One-off events from the ViewModel (price alert, error toast):
// ViewModel:
private val _events = MutableSharedFlow<String>()
val events: SharedFlow<String> = _events.asSharedFlow()
// ...inside a coroutine: _events.emit("AAPL crossed $200")

// Screen:
LaunchedEffect(Unit) {
    viewModel.events.collect { snackbarHostState.showSnackbar(it) }
}

Load more at the bottom (pagination)

// JSONPlaceholder: ?_page=1&_limit=20   ·   PokeAPI: ?offset=0&limit=20
@GET("posts")
suspend fun getPosts(@Query("_page") page: Int, @Query("_limit") limit: Int = 20): List<Post>

class FeedViewModel : ViewModel() {
    private val repository = PostRepository()
    private var page = 1
    private var loading = false

    private val _items = MutableStateFlow<List<Post>>(emptyList())
    val items: StateFlow<List<Post>> = _items.asStateFlow()
    private val _endReached = MutableStateFlow(false)
    val endReached: StateFlow<Boolean> = _endReached.asStateFlow()

    init { loadMore() }

    fun loadMore() {
        if (loading || _endReached.value) return       // no double loads
        loading = true
        viewModelScope.launch {
            try {
                val next = repository.getPosts(page)
                if (next.isEmpty()) _endReached.value = true
                else { _items.update { it + next }; page++ }
            } catch (e: Exception) {
                // keep what we have; could expose an error flag for a "Retry" row
            } finally {
                loading = false
            }
        }
    }
}

// Screen: the last row triggers the next page when it scrolls into view
LazyColumn {
    items(items, key = { it.id }) { PostRow(it) }
    if (!endReached) item {
        LaunchedEffect(items.size) { viewModel.loadMore() }
        Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
    }
}

Save favorites across app restarts (SharedPreferences)

// AndroidViewModel gets the Application (a Context). viewModel() still creates it.
class CoinListViewModel(app: Application) : AndroidViewModel(app) {
    private val prefs = app.getSharedPreferences("prefs", Context.MODE_PRIVATE)

    private val _favs = MutableStateFlow(prefs.getStringSet("favs", emptySet())!!.toSet())
    val favs: StateFlow<Set<String>> = _favs.asStateFlow()

    fun toggleFav(id: String) {
        _favs.update { if (id in it) it - id else it + id }
        prefs.edit().putStringSet("favs", _favs.value).apply()
    }
}
// imports: android.app.Application, android.content.Context, androidx.lifecycle.AndroidViewModel
// Say: "In production I'd use DataStore or Room."

Parse a JSON string or a local file (mock data, no network)

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

// From a string:
val json = """[{"id":1,"name":"Leanne","email":"a@b.c","company":{"name":"Acme"}}]"""
val users: List<User> = Gson().fromJson(json, object : TypeToken<List<User>>() {}.type)
// simpler for arrays:
val users2: List<User> = Gson().fromJson(json, Array<User>::class.java).toList()

// From a file: right-click app → New → Folder → Assets Folder, put users.json in it.
// In an AndroidViewModel (needs a Context):
val text = getApplication<Application>().assets.open("users.json").bufferedReader().use { it.readText() }

// Fake a slow network so the loading state shows:
viewModelScope.launch { delay(1_000); _state.value = UiState.Success(users) }

API that needs a key

// Key in a header, one endpoint:
@GET("v1/assets")
suspend fun getAssets(@Header("Authorization") auth: String = "Bearer $API_KEY"): AssetsResponse

// Key in a query parameter:
@GET("data") suspend fun getData(@Query("apikey") key: String = API_KEY): Data

// Key on every request: add an interceptor in ApiClient
private val client = OkHttpClient.Builder()
    .addInterceptor { chain ->
        chain.proceed(chain.request().newBuilder().addHeader("x-api-key", API_KEY).build())
    }
    .addInterceptor(logging)
    .build()

const val API_KEY = "..."   // top level in ApiClient.kt; say "in production this goes in local.properties / BuildConfig"
// imports: retrofit2.http.Header

Image placeholder, error, round crop

AsyncImage(
    model = coin.image,
    contentDescription = coin.name,
    modifier = Modifier.size(40.dp).clip(CircleShape),
    contentScale = ContentScale.Crop,
    placeholder = ColorPainter(Color.LightGray),                         // while loading
    error = rememberVectorPainter(Icons.Filled.BrokenImage)              // failed or bad URL
)
// imports: androidx.compose.ui.draw.clip, androidx.compose.foundation.shape.CircleShape,
// androidx.compose.ui.layout.ContentScale, androidx.compose.ui.graphics.painter.ColorPainter,
// androidx.compose.ui.graphics.vector.rememberVectorPainter

Confirm dialog

var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
    AlertDialog(
        onDismissRequest = { showDialog = false },
        title = { Text("Remove from watchlist?") },
        confirmButton = { TextButton(onClick = { viewModel.remove(id); showDialog = false }) { Text("Remove") } },
        dismissButton = { TextButton(onClick = { showDialog = false }) { Text("Cancel") } }
    )
}

Debounced search (only filter after typing pauses)

@OptIn(FlowPreview::class)
val visible = combine(_state, _query.debounce(300)) { state, q -> /* filter as before */ }
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)
// Say: "With server-side search I'd debounce so we don't fire a request per keystroke."

Dates from JSON

// "2026-12-01T16:00:00Z" → "Dec 1, 4:00 PM"  (minSdk 26, so java.time works)
val formatted = Instant.parse(iso)
    .atZone(ZoneId.systemDefault())
    .format(DateTimeFormatter.ofPattern("MMM d, h:mm a"))
// imports: java.time.Instant, java.time.ZoneId, java.time.format.DateTimeFormatter