MongoDB Java Async Driver: Block <Document> vs SingleResultCallBack <Document>

I just started learning the asynchronous mongodb java driver API. Most examples override the SingleResultCallback onResult method , as shown below:

 // get it (since it 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());
        }
    });    

this callback is executed when the request is executed and a response / error is returned.

But in the case of FindIterable, we need to redefine the block application method as the 1st argument and the SingleResultCallback onResult method as the sencond argument.

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");
        }
    });

I cannot understand why we need both Block and SingleResultCallBack at the same time. What things / operations can we perform in a block that we could not do with SingleResultCallBack?

+4
1

Block . SingleResultCallback .

javadoc com.mongodb.async.client.MongoIterable :

, , , .

0

Source: https://habr.com/ru/post/1599285/


All Articles