MongoDB Java异步驱动程序:Block<Document> vs SingleResultCallback<Document>

4

我刚开始学习mongodb java驱动的异步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中完成的?

1个回答

0

Block 应用于迭代的每个项。 在迭代完成后,SingleResultCallback 会被执行一次。

关于 com.mongodb.async.client.MongoIterablejavadoc 表示:

迭代查看中的所有文档,对每个文档应用给定的 block,并在所有文档都已迭代或出现异常后完成返回的 future。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接