从方法中获取 int 值,该方法在后台线程上执行
Get int value from method, which executes on background thread
我正在使用 Google 架构组件,尤其是 Room。
在我的 Dao 中我有这个方法:
@Query("SELECT COUNT(*) FROM photos")
int getPersistedPhotosSize();
我需要在我的存储库中执行它以检查持久化照片大小是否为 0。
所以我必须在后台执行这个方法并从中获取值。
现在我这样执行这个操作:
public int getNumRowsFromFeed() {
final int[] rows = new int[1];
Completable.fromAction(() -> rows[0] = photosDao.getPersistedPhotosSize())
.subscribeOn(Schedulers.io())
.blockingAwait();
return rows[0];
}
但我想这不是最好的方法。
那么我怎样才能以正确的方式获得价值呢?特别是我想 without RX
在您的 DAO 中,获取照片计数的函数既不使用 LiveData
也不使用 RX
。因此,您基本上可以使用任何 Android 异步技术,而不是事后将代码包装在 Completable
中,例如 AsyncTask
。
public class LoadTask extends AsyncTask<Void, Void, Integer> {
public interface Callback {
void onPhotoCount(int count);
}
private final Callback callback;
public LoadTask(Callback callback) {
this.callback = callback;
}
protected Integer doInBackground(Void... params) {
return photosDao.getPersistedPhotosSize();
}
protected void onPostExecute(Integer result) {
callback.onPhotoCount(result);
}
}
...
new LoadTask(photoCount -> {
// Do stuff with value,e.g. update ui.
}).execute();
这基本上只是一个提议,当然你也可以使用Threads、Handler。
P.S:在我看来,这个例子显示了 Rx
开发的一个优势。您可以免费获得回调内容,无需定义任何内容。例如,由于生命周期事件,您可以取消 Rx 链。这在这个例子中没有实现。
我正在使用 Google 架构组件,尤其是 Room。
在我的 Dao 中我有这个方法:
@Query("SELECT COUNT(*) FROM photos")
int getPersistedPhotosSize();
我需要在我的存储库中执行它以检查持久化照片大小是否为 0。
所以我必须在后台执行这个方法并从中获取值。
现在我这样执行这个操作:
public int getNumRowsFromFeed() {
final int[] rows = new int[1];
Completable.fromAction(() -> rows[0] = photosDao.getPersistedPhotosSize())
.subscribeOn(Schedulers.io())
.blockingAwait();
return rows[0];
}
但我想这不是最好的方法。
那么我怎样才能以正确的方式获得价值呢?特别是我想 without RX
在您的 DAO 中,获取照片计数的函数既不使用 LiveData
也不使用 RX
。因此,您基本上可以使用任何 Android 异步技术,而不是事后将代码包装在 Completable
中,例如 AsyncTask
。
public class LoadTask extends AsyncTask<Void, Void, Integer> {
public interface Callback {
void onPhotoCount(int count);
}
private final Callback callback;
public LoadTask(Callback callback) {
this.callback = callback;
}
protected Integer doInBackground(Void... params) {
return photosDao.getPersistedPhotosSize();
}
protected void onPostExecute(Integer result) {
callback.onPhotoCount(result);
}
}
...
new LoadTask(photoCount -> {
// Do stuff with value,e.g. update ui.
}).execute();
这基本上只是一个提议,当然你也可以使用Threads、Handler。
P.S:在我看来,这个例子显示了 Rx
开发的一个优势。您可以免费获得回调内容,无需定义任何内容。例如,由于生命周期事件,您可以取消 Rx 链。这在这个例子中没有实现。