I am trying to tinker with the new Room library in pairing it with RxJava.
I've found a way to use a Single
to insert items on the background thread like this, inside of an activity:
Single.fromCallable { AppDatabase.getInMemoryDatabase(this).taskDao().insertAll(task) }
.subscribeOn(Schedulers.newThread())
.subscribe()
Now, I have a RecyclerView with tasks that has a checkbox you can use to mark an item as complete or not. What I want to do is update the item each time it is checked/unchecked. I'll paste the whole ViewHolder for completion, but note specifically the lambda in bindTask()
:
inner class TaskViewHolder(view: View?) : RecyclerView.ViewHolder(view) {
val descriptionTextView = view?.findViewById(R.id.task_description) as? TextView
val completedCheckBox = view?.findViewById(R.id.task_completed) as? CheckBox
fun bindTask(task: Task) {
descriptionTextView?.text = task.description
completedCheckBox?.isChecked = task.completed
completedCheckBox?.setOnCheckedChangeListener { _, isChecked ->
tasks[adapterPosition].completed = isChecked
Single.fromCallable { itemView.context.taskDao().update(tasks[adapterPosition]) }
.subscribeOn(Schedulers.newThread())
.subscribe()
}
}
}
This works for the first item I check, but after that I'm unable to click any other checkboxes. I thought the Single
would destroy itself, but perhaps I can't do this inside the lambda? Do I need to pull the Single outside of it somehow?