mardi 2 février 2016

RxJava with SQlite and ContentProvider operations

I'm studying RxJava and to do this I'm playing with SQLite, writing an helper class SQLiteUtils in order to help handling asynchronous ContentResolver queries easier. For example this is the queryInBackground method:

static
public <T> Observable<T> queryInBackground(
        final ContentResolver cr,
        final Uri uri,
        final String[] projection,
        final String selection,
        final String[] selectionArgs,
        final String sortOrder,
        final CursorHandler<T> ch) {
    return  Observable.create(new Observable.OnSubscribe<T>() {
        @Override
        public void call(Subscriber<? super T> observer) {
            if (!observer.isUnsubscribed()) {
                Cursor cursor = null;
                try {
                    cursor = cr.query(uri, projection, selection, selectionArgs, sortOrder);
                    if (cursor != null && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            observer.onNext(ch.handle(cursor));
                        }
                    }
                    observer.onCompleted();
                } catch (Exception err) {
                    observer.onError(err);

                } finally {
                    if (cursor != null) cursor.close();
                }
            }
        }
    }).subscribeOn(Schedulers.computation());
}

where CursorHandler is an interface:

/**
 * Implementations of this interface convert Cursor into other objects.
 *
 * @param <T> the target type the input Cursor will be converted to.
 */
public interface CursorHandler<T> {
    T handle(Cursor cu) throws SQLException;
}

I've read the docs about Schedulers, but I'm not quite sure if Schedulers.computation() was the right choice.

And if I'd like to implements something similiar for basic HttpUrlConnection operations, wich Scheduler I should pick? Schedulers.newThread() or Schedulers.io(), I'd stick with Schedulers.io() ...but not sure.

Thanks in advance.

All the best, luca

Aucun commentaire:

Enregistrer un commentaire