android / architecture-samples

A collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
Apache License 2.0
44.16k stars 11.6k forks source link

[Data layer codelab] Section 7 (Create the task repository) should reuse mapped data #994

Open hecosw opened 5 months ago

hecosw commented 5 months ago

Here: suspend fun refresh() { val networkTasks = networkDataSource.loadTasks() localDataSource.deleteAll() val localTasks = withContext(dispatcher) { networkTasks.toLocal() } localDataSource.upsertAll(networkTasks.toLocal()) }

The last line should probably read: localDataSource.upsertAll(networkTasks.toLocal())

iencotech commented 4 months ago

I think it should use the localTasks instead of converting the network tasks to local again, otherwise the withContext() has no purpose:

suspend fun refresh() {
    val networkTasks = networkDataSource.loadTasks()
    localDataSource.deleteAll()
    val localTasks = withContext(dispatcher) {
        networkTasks.toLocal()
    }
    localDataSource.upsertAll(localTasks) // Fixed this line
}
MahdiRahmani80 commented 3 months ago

I got this problem and I fixed this another way! I've gone to FakeTaskDao.kt and added this line tasksStream.emit(tasks) my code now looks like this:

  override suspend fun upsertAll(tasks: List<LocalTask>) {
    val newTaskIds = tasks.map { it.id }
    _tasks.removeIf { newTaskIds.contains(it.id) }
    _tasks.addAll(tasks)
    tasksStream.emit(tasks) // this line
  }

I think this solution is a little bit better, because the upsertAll function doesn't emit newly updated tasks.