In my opinion the right thing to do is to delegate the query to an IO thread using RxJava.
I have an example of a solution to an equivalent problem I've just encountered.
((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.VISIBLE);//Always good to set some good feedback
Completable.fromAction(() -> {
//Creating view model requires DB access
homeViewModel = new ViewModelProvider(this, factory).get(HomeViewModel.class);
}).subscribeOn(Schedulers.io())//The DB access executes on a non-main-thread thread
.observeOn(AndroidSchedulers.mainThread())//Upon completion of the DB-involved execution, the continuation runs on the main thread
.subscribe(
() ->
{
mAdapter = new MyAdapter(homeViewModel.getExams());
recyclerView.setAdapter(mAdapter);
((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.INVISIBLE);
},
error -> error.printStackTrace()
);
And if we want to generalize the solution:
((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.VISIBLE);//Always good to set some good feedback
Completable.fromAction(() -> {
someTaskThatTakesTooMuchTime();
}).subscribeOn(Schedulers.io())//The long task executes on a non-main-thread thread
.observeOn(AndroidSchedulers.mainThread())//Upon completion of the DB-involved execution, the continuation runs on the main thread
.subscribe(
() ->
{
taskIWantToDoOnTheMainThreadWhenTheLongTaskIsDone();
},
error -> error.printStackTrace()
);