繁体   English   中英

RxJava具有SQlite和ContentProvider操作

[英]RxJava with SQlite and ContentProvider operations

我正在研究RxJava,为此我正在使用SQLite,编写一个辅助类SQLiteUtils ,以帮助更轻松地处理异步ContentResolver查询。 例如,这是queryInBackground方法:

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());
}

其中CursorHandler是一个接口:

/**
 * 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;
}

我已经阅读了有关调度程序的文档,但我不太确定Schedulers.computation()是否是正确的选择。

如果我想实现类似于基本HttpUrlConnection操作的东西,我应该选择哪个Scheduler? Schedulers.newThread()Schedulers.io() ,我坚持使用Schedulers.io() ...但不确定。

提前致谢。

一切顺利,卢卡

根据这个答案你应该使用Schedulers.io() 相关报价:

io()由无限制的线程池支持,并且是非计算密集型任务所使用的东西,即不会给CPU带来太多负担的东西。 因此,与文件系统的交互,与不同主机上的数据库或服务的交互就是很好的例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM