Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Instruction

This section covers CRUD operations and how to perform them in Room databases. You’ll learn to create, read, update, and delete data.

Understanding CRUD Operations

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that you can perform on a database. You use these main operations to interact with the data in a database.

Exploring CRUD Operations in Room Databases

In Room database, you use Data Access Objects (DAOs) to define the operations that you want to perform on the database. You can use these operations to create, read, update, and delete data in the database. You have already learned about DAOs in the previous section.

interface NotesRepository {
  suspend fun saveNote(noteEntity: NoteEntity)
  fun getNotes(): Flow<List<NoteEntity>>
  suspend fun update(noteEntity: NoteEntity)
  suspend fun delete(noteEntity: NoteEntity)
}
class NotesRepositoryImpl(
  private val ioDispatcher: CoroutineDispatcher,
  private val notesDao: NotesDao
): NotesRepository {
  override suspend fun saveNote(noteEntity: NoteEntity) {
    withContext(ioDispatcher) {
      notesDao.insert(noteEntity)
    }
  }

  override fun getNotes(): Flow<List<NoteEntity>> {
    return notesDao.getNotes()
  }

  override suspend fun update(noteEntity: NoteEntity) {
    withContext(ioDispatcher) {
      notesDao.update(noteEntity)
    }
  }

  override suspend fun delete(noteEntity: NoteEntity) {
    withContext(ioDispatcher) {
      notesDao.delete(noteEntity)
    }
  }
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo: Create & Read Notes from Room Database