android5-3 Exercise 1: The stateIn ViewModel ========================================= import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext // A fake data source for now: Chapters 4 to 7 replace it with Room and Retrofit class FakeNotesRepository( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { private val _notes = MutableStateFlow(listOf("Buy milk", "Call Ada")) // A Flow: it emits the current list now and again after every change val notes: Flow> = _notes.asStateFlow() // Main-safe: callers can use it from the main thread suspend fun addNote(text: String) = withContext(ioDispatcher) { delay(300) // pretend this is slow if (text == "fail") error("Could not save") _notes.update { it + text } } } import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class NotesViewModel( private val repository: FakeNotesRepository = FakeNotesRepository() ) : ViewModel() { private val message = MutableStateFlow(null) // Built from the data layer's Flow: no loading code in init val uiState: StateFlow = combine(repository.notes, message) { notes, userMessage -> NotesUiState(notes = notes, isLoading = false, userMessage = userMessage) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun addNote(text: String) { if (text.isBlank()) { message.value = "A note cannot be empty" return } viewModelScope.launch { try { repository.addNote(text) } catch (e: CancellationException) { throw e // never swallow cancellation } catch (e: Exception) { message.value = "Could not save the note" } } } fun messageShown() { message.value = null } } NotesUiState and the Chapter 2 composables stay as they are. Expected: the screen stays responsive during the 300 ms delay (the work is a suspend function on the IO dispatcher, not blocking the main thread); the loading text may appear only for a moment at start-up because the repository emits immediately. Report what you saw. Code unrun.