I have a big database which takes time to find needed information. So I decided to use RxJava to make this process asynchronous.
@Override
public void afterTextChanged(final Editable s) {
final String query = s.toString();
Observable.create(new Observable.OnSubscribe<Cursor>() {
@Override
public void call(Subscriber<? super Cursor> subscriber) {
subscriber.onNext(database.search(query));
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Cursor>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Cursor cursor) {
scAdapter.swapCursor(cursor);
}
});
}
But query is running on main thread: EditText where I entering text is freezing.
My question is how to run SQLite query asynchronously on background thread?
Probably this https://developer.android.com/reference/android/app/LoaderManager.html will suite for you.
Besides, here is short implementation for you, but this is not RxJava.
Firstly, you need to implement
LoaderManager.LoaderCallbacks<Cursor>
, and usually this interface is implemented by Activity (or Fragment).In
onCreateLoader
, aCursorLoader
should be created and returned. Here is just an example with MyCursorLoader as descendant ofCursorLoader
, where you can perform connection to database and queries.In
onLoadFinished
you have to treat cursor with results of query.Please, consider the link to android.com, mentioned above.
Another way, is in using of
ContentProvider
https://developer.android.com/guide/topics/providers/content-providers.html .In this way you can separate data layer and business logic. Your data access will be abstracted to uris. Using
ContentProvider
, you define your queries within it and load data using Uri:This is convenient way if you have more than one or two customers of your data (Activities or Fragments) - you will use just predefined uris rather repeating sql queries or creating many CursorLoaders
descendands
.Moreover,
ContentProvider
may be used from outside your app if you want.