Challenge 2: A ViewModel Backed by Room — Solution class NoteViewModel(private val dao: NoteDao) : ViewModel() { val notes: StateFlow> = dao.getAllNotes() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) fun addNote(title: String, content: String) { viewModelScope.launch { dao.insert(Note(title = title, content = content)) } } } Notes: - dao.getAllNotes() returns a cold Flow> straight from Room; .stateIn(...) converts it into a hot StateFlow that Compose can collect with collectAsStateWithLifecycle(), following the exact same pattern as the chapter's TaskViewModel example. - initialValue = emptyList() is what "notes" holds before the very first emission from the database arrives — collectAsStateWithLifecycle() never sees an uninitialized/null state this way. - addNote() wraps dao.insert(...) — a suspend function — in viewModelScope.launch { }, since insert() can't be called directly from a non-suspending context like a Button's onClick lambda. - WhileSubscribed(5000) means the underlying database query keeps running for 5 seconds after the last UI collector disappears (e.g. during a brief rotation), rather than stopping and restarting immediately, avoiding an unnecessary re-query.