SqlBrite Queries on Worker Threads

453 views Asked by At

I'm still somewhat new to rxAndroid/rxJava so I'm having a little trouble wrapping my mind around this and if I'm doing everything correctly.

I am using SqlBrite to update a RecyclerView with rows returned from a Cursor. When a db operation is performed on the table, the observable below is responsible for re-querying the data. I want to return a CursorWrapper (ChecklistCursor), but want to make sure I am running the select * query on a worker thread. The checklistRecyclerAdapter subscribes to the ChecklistCursor observable and is responsible for managing the cursor.

The code below seems to be the only way that I am able to get query.run() to run on a worker thread and the subscription to return on the main thread.

I guess it works, but I don't believe this would be the standard way to do this. Could anyone offer a better method than using observeOn twice?

compositeSubscription.add(db.createQuery(Checklist.TABLE, Checklist.QUERY_ALL)
    .observeOn(Schedulers.newThread())
    .map(query -> new ChecklistCursor(query.run()))
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(checklistListRecyclerAdapter));
1

There are 1 answers

1
Victor Manuel Pineda Murcia On

I would replace the first observeOn call with subscribeOn(Schedulers.io()), in order to perform the query operation in a background thread. Map operator will still perform the operation in the background thread, and after that, you can change with observeOn to update your adapter. I think this is the only way to do this.