I'm making a DB request and getting back a list of objects. Within this list of objects is another list, which I want to filter on. After filtering, I then want to map the remaining objects to my domain model.
So I have my Database model:
data class TaskDatabaseModel(
@PrimaryKey
@ColumnInfo(name = "id")
var id: String,
@ColumnInfo(name = "task_categories")
val categories: List<TaskCategory>,
//Other fields
)
And my domain model:
@Parcelize
data class Task(
val id: String,
val taskCategories: List<TaskCategory> = listOf(TaskCategory(TaskCategoryType.GENERAL)),
//Other fields
) : Parcelable
TaskCategory:
@Parcelize
data class TaskCategory(val type: TaskCategoryType, val id: String? = null) : Parcelable
My function to get the list:
override fun getTasks(taskId: String): Flowable<List<Task>> {
return db.getTasksDao().getAllTasks()
.map { taskList ->
taskList.map { listTaskDbModel ->
listTaskDbModel.mapToDomainModel(cache.getCurrentUserId())
}
}
.filter { taskList ->
taskList.find { it.taskCategories.find { category -> category.id == taskId } != null } != null
}
}
The filter code returns all items and doesn't filter.
How do I change it so I only return the objects that have the required id in the categories list? Would it be easier to do it on the DB query? The list is stored as JSON.
Thanks
Flowablerather than ontaskList. This means that if at least one task matches your condition, you'll keep all tasks. More generally, if you can do a filter in the DB query, it's likely faster...