android5-5 Exercise 1: Repository end to end ========================================= // The model the UI and the ViewModel use: plain data, no Room annotations data class Note( val id: Long, val text: String, val createdAt: Long ) // Mapping between the storage class (Chapter 4) and the model fun NoteEntity.toModel() = Note(id = id, text = text, createdAt = createdAt) fun Note.toEntity() = NoteEntity(id = id, text = text, createdAt = createdAt) import kotlinx.coroutines.flow.Flow interface NotesRepository { // Naming convention for a function that returns a Flow: getXxxStream fun getNotesStream(): Flow> suspend fun addNote(text: String) suspend fun deleteNote(note: Note) } import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class DefaultNotesRepository( private val noteDao: NoteDao ) : NotesRepository { override fun getNotesStream(): Flow> = noteDao.observeNotes().map { entities -> entities.map { it.toModel() } } override suspend fun addNote(text: String) { noteDao.insert(NoteEntity(text = text)) } override suspend fun deleteNote(note: Note) { noteDao.delete(note.toEntity()) } } data class NotesUiState( val notes: List = emptyList(), // was List val isLoading: Boolean = false, val userMessage: String? = null ) class NotesViewModel( private val repository: NotesRepository // the interface, not the Room class ) : ViewModel() { private val message = MutableStateFlow(null) val uiState: StateFlow = combine(repository.getNotesStream(), 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 } catch (e: Exception) { message.value = "Could not save the note" } } } fun deleteNote(note: Note) { viewModelScope.launch { repository.deleteNote(note) } } fun messageShown() { message.value = null } companion object { // A small hand-written factory: Chapter 9 explains and tidies this val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val app = this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as NotesApp NotesViewModel(app.notesRepository) } } } } class NotesApp : Application() { val database: AppDatabase by lazy { Room.databaseBuilder(applicationContext, AppDatabase::class.java, "notes.db").build() } // The one place that builds the repository val notesRepository: NotesRepository by lazy { DefaultNotesRepository(database.noteDao()) } } @Composable fun NotesRoute(viewModel: NotesViewModel = viewModel(factory = NotesViewModel.Factory)) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() NotesScreen( state = uiState, onAddNote = viewModel::addNote, onDeleteNote = viewModel::deleteNote, onMessageShown = viewModel::messageShown ) } // In the list, the screen now shows note.text: items(state.notes) { note -> Text(note.text) } Expected: the notes survive closing and reopening, because they are stored in Room (Chapter 4), not in memory. Report what you saw. If the build fails on the factory, check the imports for viewModelFactory, initializer and APPLICATION_KEY, and that the manifest names NotesApp. Code unrun.