Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hecosw opened this issue Feb 13, 2024 · 3 comments

Comments

@hecosw
Copy link

hecosw commented Feb 13, 2024

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
Copy link

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
Copy link

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.

@Fe1777
Copy link

Fe1777 commented Jun 6, 2024

Sure! It sounds like you're referring to an issue or a suggestion related to the official Android Architecture Components samples, specifically around improving the data layer in the context of a codelab.

Here's a more detailed approach to your concern about reusing mapped data in the TaskRepository implementation within the context of section 7 of the codelab:

Objective

  • Enhance the repository to leverage mapped data, avoiding redundant computations or transformations.

Steps to Reuse Mapped Data in TaskRepository


1. Review Existing Structure

  • TaskRepository

    • Handles data operations and provides a clean API for data access to the rest of the application.
  • Data Mapping

    • Typically involves converting between entities (database objects) and domain models (business logic objects).

2. Using In-Memory Cache for Mapped Data

One approach to reuse the mapped data is to introduce an in-memory cache within the TaskRepository. This cache can store the transformed/mapped data to minimize redundant work.

Example:

class TaskRepository(private val taskDao: TaskDao) {

    // In-memory cache
    private val taskCache = mutableMapOf<String, Task>()

    suspend fun getTask(taskId: String): Task? {
        // Check the cache first
        taskCache[taskId]?.let {
            return it
        }

        // If not in cache, fetch from database and map it
        val taskEntity = taskDao.getTask(taskId) ?: return null
        val task = taskEntity.toDomainModel()

        // Store the mapped data in cache
        taskCache[taskId] = task

        return task
    }

    suspend fun updateTask(task: Task) {
        // Update database
        taskDao.updateTask(task.toEntity())

        // Update the cache
        taskCache[task.id] = task
    }

    // Other repository methods...
}

3. Optimize Mapping Logic

  • Ensure that your mapping logic is encapsulated in extension functions or separate mappers to maintain a single source of truth and to centralize the conversion logic.

Example Extension Functions:

fun TaskEntity.toDomainModel(): Task {
    return Task(id, name, description, isCompleted)
}

fun Task.toEntity(): TaskEntity {
    return TaskEntity(id, name, description, isCompleted)
}

Code Changes to Architecture Components Sample (PR #994)

Update your repository as follows to incorporate cache-based reuse of mapped data. The following pseudo-code assumes you have a basic understanding of the codebase.

  1. Modify TaskRepository to Include Cache:

Make sure to update the TaskRepository to use a cache for mapped data.

class TaskRepository(private val taskDao: TaskDao) {

    private val taskCache = mutableMapOf<String, Task>()

    suspend fun getTask(taskId: String): Task? {
        taskCache[taskId]?.let {
            return it
        }
        
        // Fetch and map
        val taskEntity = taskDao.getTaskById(taskId) ?: return null
        val task = taskEntity.toDomainModel()
        taskCache[taskId] = task
        return task
    }

    // Other methods...
}
  1. Ensure Mapping Functions are in a Centralized Location:

Put your mapping functions in a convenient file/module which ensures that the mappings are consistent across usages.

// TaskMapper.kt
fun TaskEntity.toDomainModel(): Task {
    return Task(id = this.id, name = this.name, description = this.description, isCompleted = this.isCompleted)
}

fun Task.toEntity(): TaskEntity {
    return TaskEntity(id = this.id, name = this.name, description = this.description, isCompleted = this.isCompleted)
}

Conclusion

By implementing an in-memory cache within the TaskRepository and ensuring all data transformations are centralized, you can greatly reduce redundant transformations and optimize data operations. This approach should fit well into the architecture and coding practices advocated by the Android Architecture Components and its corresponding codelabs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants