Save User State

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Koala | 2024.1.1

Lesson 06: CRUD Operations

Demo: Create & Read Notes from Room Database

Episode complete

Play next episode

Next

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

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

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

Unlock now

In this section, you’ll create a repository that performs some of the CRUD operations from your database.

suspend fun saveNote(noteEntity: NoteEntity)
fun getNotes(): Flow<List<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()
  }
}
val dispatcherModule = module { single { Dispatchers.IO } }

val repositoryModule = module {
  single<NotesRepository> { NotesRepositoryImpl(get(), get()) }
}
val appModules = listOf(
  dataStoreModule,
  viewModelModule,
  notesFileManagerModule,
  roomDatabaseModule,
  repositoryModule,
  dispatcherModule
)
class MainViewModel(
  private val dataStoreManager: DataStoreManager,
  private val internalNotesFileManager: InternalNotesFileManager,
  private val externalNotesFileManager: ExternalNotesFileManager,
  private val notesRepository: NotesRepository
): ViewModel() {
  // Rest of the code
}
"Room Database" -> {
  notesRepository.saveNote(noteEntity)
}
private fun fetchNotes() {
  viewModelScope.launch {
    notesRepository.getNotes().collect { notes ->
      _notes.update {
        notes + externalNotesFileManager.readTextFile() + internalNotesFileManager.readTextFile()
      }
    }
  }
}
  viewModel { MainViewModel(get(), get(), get(), get()) }
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Demo: Update & Delete Notes from Room Database