gpt4 book ai didi

android - RxJava 与 SQlite 和 ContentProvider 操作

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:27 27 4
gpt4 key购买 nike

我正在研究 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 是一个接口(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;
}

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

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

提前致谢。

祝一切顺利,卢卡

最佳答案

根据 this answer你应该使用 Schedulers.io()。相关引用:

io() is backed by an unbounded thread-pool and is the sort of thing you'd use for non-computationally intensive tasks, that is stuff that doesn't put much load on the CPU. So yep interaction with the file system, interaction with databases or services on a different host are good examples.

关于android - RxJava 与 SQlite 和 ContentProvider 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com