【发布时间】:2015-11-26 20:10:54
【问题描述】:
我在 Android 中有一个异步的基于 Retrofit 的 API 调用,需要等待数据库调用,直到 API 调用完成,这样我才能确定正确的数据被输入到数据库中。
我读到您可以使用 Futures 来完成此任务,但是在我当前的实现中,我得到了一个空指针异常。
API方法如下:
public Future<Void> postPrintMode(String authorization, final int userid, String deviceuid, final Map payload){
api.postPrintMode(authorization, userid, deviceuid, payload, new Callback<PrintMode>() {
@Override
public void success(PrintMode printMode, Response response) {
if (printMode.get_id() != 0) {
dbOps.writePrintMode(userid, printMode);
bus.getBus().post(new EVTNewPrintMode(printMode));
}
}
@Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace();
APIUtils.showAPIResponseBody(retrofitError);
}
});
return null;
}
这里是我要确保在继续读取数据库结果之前执行异步代码的块。
Future<Void> f = APIExec.getInstance().postPrintMode(IConstants.authorization, IConstants.userId, IConstants.deviceUid, payload);
// here I get the null pointer exception
f.get();
// the code below needs to be executed after the postPrintMode(...) async method;
DBPrintMode printMode = APIDBOps.getInstance().readPrintModeByPrintModeID(6);
assertNotNull("Print Mode does not exist", printMode);
【问题讨论】:
-
我不认为
Future是你想要的。 (例如,您需要一个同步调用来在可运行文件中进行改造)。您的模式更适合阻塞队列、倒计时锁或信号量 -
你说得对,我使用了 CountDownLatch 并全局存储了倒计时信号,并在异步方法成功或失败时递减。
-
stored globally the countdown signal你可以在你的方法中声明它为final并返回它。
标签: android asynchronous retrofit concurrent.futures