【发布时间】:2015-07-23 11:50:08
【问题描述】:
我刚开始学习 mongodb java driver 的 async API。大多数示例会覆盖 SingleResultCallback 的 onResult 方法,如下所示:
// get it (since it's the only one in there since we dropped the rest earlier on)
collection.find().first(new SingleResultCallback<Document>() {
@Override
public void onResult(final Document document, final Throwable t) {
System.out.println(document.toJson());
}
});
当查询被执行并返回响应/错误时执行此回调。
但是,在 FindIterable 的情况下,我们需要重写 Block 的 apply 方法作为第一个参数,并将 SingleResultCallback 的 onResult 方法作为第二个参数。
FindIterable<Document> iterable = db.getCollection("restaurants").find();
// @code: end
// @pre: Iterate the results and apply a block to each resulting document
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
}, new SingleResultCallback<Void>() {
@Override
public void onResult(final Void result, final Throwable t) {
System.out.println("Operation Finished");
}
});
我无法理解为什么我们同时需要 Block 和 SingleResultCallBack。我们可以在 Block 中执行哪些 SingleResultCallBack 无法执行的操作/操作?
【问题讨论】:
标签: mongodb mongodb-java