[Data layer codelab] Small error in 'refresh()' method in Chapter 7
In chapter 7 "Create the Task Repository", and in the 2nd step of section "Save and refresh network data", the code block suggests we do
suspend fun refresh() {
val networkTasks = networkDataSource.loadTasks()
localDataSource.deleteAll()
val localTasks = withContext(dispatcher) {
networkTasks.toLocal()
}
localDataSource.upsertAll(networkTasks.toLocal()) // THIS IS THE ERROR
}
as you can see, localTasks is pointless here because you are doing the same thing in the erroneous line but you are also blocking the main thread. Instead, it should look like this
suspend fun refresh() {
val networkTasks = networkDataSource.loadTasks()
localDataSource.deleteAll()
val localTasks = withContext(dispatcher) {
networkTasks.toLocal()
}
localDataSource.upsertAll(localTasks) // CORRECTED LINE
}
Issue Summary In the original code:
val localTasks = withContext(dispatcher) { networkTasks.toLocal() } localDataSource.upsertAll(networkTasks.toLocal()) // Problem localTasks is computed on a background dispatcher, which is the correct behavior.
However, the next line recomputes networkTasks.toLocal() on the main thread, defeating the purpose and wasting resources.
Worse, it ignores the optimized localTasks already computed.
Corrected Version
val localTasks = withContext(dispatcher) { networkTasks.toLocal() } localDataSource.upsertAll(localTasks) // Uses already transformed data This version:
Avoids double computation.
Keeps CPU-bound toLocal() work off the main thread.
Is consistent with good coroutine practices.
Recommendation If you're submitting this as a GitHub issue or pull request to the official codelab repo, your explanation and correction are spot-on. You could summarize it like:
"Avoid redundant .toLocal() call and ensure proper use of the transformed result already computed on the background dispatcher."