Challenge 1: A ViewModel-Backed Counter — Solution class CounterViewModel : ViewModel() { private val _count = MutableStateFlow(0) val count: StateFlow = _count.asStateFlow() fun increment() { _count.value++ } } @Composable fun CounterScreen(viewModel: CounterViewModel = viewModel()) { val count by viewModel.count.collectAsStateWithLifecycle() Column(modifier = Modifier.padding(16.dp)) { Text(text = "Count: $count", fontSize = 20.sp) Button(onClick = { viewModel.increment() }) { Text("Increment") } } } // MainActivity.kt class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CounterScreen() } } } Testing steps: 1. Run the app, tap Increment several times (e.g. to 5). 2. Rotate the emulator. 3. Confirm the count still shows 5, not reset to 0 — unlike Chapter 1's remember-based Counter, which would have reset. Notes: - viewModel: CounterViewModel = viewModel() is a default parameter using the viewModel() composable function — on first call it creates a CounterViewModel scoped to the hosting Activity; on every SUBSEQUENT call (including after rotation recreates the Activity) it returns the SAME instance rather than creating a new one. - That "same instance returned again" behavior is exactly what makes the count survive rotation — the ViewModel itself was never destroyed, only the Activity and its Compose UI were recreated around it. - collectAsStateWithLifecycle() bridges the ViewModel's StateFlow into Compose's recomposition system, exactly like remember { mutableStateOf(...) } did in Chapter 1, just backed by a ViewModel-owned StateFlow instead.