MongoDB Java Reactive Streams help

I know how to insert documents from http://mongodb.github.io/mongo-java-driver-reactivestreams/1.13/getting-started/quick-tour/, but how to get the document from db when collection.find().first().subscribe(subscriber); returns Publisher ? Also if all actions are performed async how to make it sync ?

Hello @Zdziszkee_N_A,

… how to get the document from db when collection.find().first().subscribe(subscriber); returns Publisher?

collection.find().first() returns a org.reactivestreams.Publisher<TResult>.

The Publisher's subscibe(Subscriber<? super T> s) method “Requests Publisher to start streaming data.” - it doesn’t return a Publisher.

The tutorial’s examples have a subscriber defined; use that code. There is an example PrintSubscriber, and this can be used to print the find query result.

The SubscriberHelpers is a utility class shown with the examples. It is used as shown in the Quick Tour. The source code for the SubscriberHelpers.java can be found on GitHub: https://github.com/mongodb/mongo-java-driver-reactivestreams/tree/master/examples/tour/src/main/tour. You can use it with your program.

Also if all actions are performed async how to make it sync ?

I guess, you can try using the synchronous Java APIs for those .

Okay but how to get the Document object itself from that ? Casting ?

The Quick Tour - Query the Collection - Find the First Document in a Collection has the code snippet:

subscriber = new PrintDocumentSubscriber();
collection.find().first().subscribe(subscriber);
subscriber.await();

When this code gets executed, it prints the first document from the collection. The print happens using the PrintDocumentSubscriber (which has a description: “A Subscriber that prints the json version of each document”) from the SubscriberHelpers class (I have already provided the link in the previous post).

I don’t think casting is way to get your document. It looks like you have to use the SubscriberHelpers class API for the tutorial, or build your own helpers / code to do the tasks you have on your mind.

1 Like

Hi,

The reactive streams API is fairly low level API and was designed to be a foundation for async stream processing in Java. There are libraries that extend the reactive streams API and make them much more user friendly:

  • Rx Java - The ReactiveX project is really well explained and has many helpers to aid the use of reactive streams.
  • Project Reactor - From the Spring team, a smaller library that is packed full of great features.

I would suggest using a higher level library to aid the use of Publishers by making them easier to consume.

Ross

1 Like