【问题标题】:MongoDB Java Async Driver: Block<Document> vs SingleResultCallBack<Document>MongoDB Java 异步驱动程序:Block<Document> 与 SingleResultCallBack<Document>
【发布时间】: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


    【解决方案1】:

    Block 应用于迭代的每个项目。 SingleResultCallback 在迭代完成后执行。

    javadoccom.mongodb.async.client.MongoIterable 表示:

    遍历视图中的所有文档,将给定的块应用于 每个,并在所有文件都完成后完成返回的未来 迭代,或发生异常。

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多