MongoDB Reactive Streams driver
In the previous sections, we took an overview of the support for Reactive Streams from the reactive libraries and framework perspective. However, the area of the specification's application is not limited to frameworks or reactive libraries only. The same rule of interaction between the producer and consumer can be applied to communication with a database via a database driver.
In that way, MongoDB provides a Reactive Streams-based driver along with callback-based and RxJava 1.x drivers. In turn, MongoDB provides additional, fluent API implementation, which gives some sort of querying based on the written transformation. For example, the internal implementation of DBPublisher that we might have seen in the news service example potentially may be implemented in the following way:
public class DBPublisher implements Publisher<News> { // (1)
private final MongoCollection<News> collection; //
private final Date publishedOnFrom; //
public DBPublisher( // (2)
MongoClient client, //
Date publishedOnFrom //
) { ... } //
@Override // (3)
public void subscribe(Subscriber<? super News> s) { //
FindPublisher<News> findPublisher = // (3.1)
collection.find(News.class); //
//
findPublisher // (3.2)
.filter(Filters.and( //
Filters.eq("category", query.getCategory()), //
Filters.gt("publishedOn", today()) //
) //
.sort(Sorts.descending("publishedOn")) //
.subscribe(s); // (3.3)
} //
}
The key is as follows:
- This is the DBPublisher class and related fields declaration. Here, the publishedOnFrom field refers to the date after which the news posts should be searched.
- This is the constructor declaration. Here, one of the accepted parameters in the DBPublisher's constructor is the configured MongoDB client, which is com.mongodb.reactivestreams.client.MongoClient.
- This is the Publisher#subscriber method implementation. Here, we simplified the DBPublisher's implementation by using the FindPublisher from the Reactive Streams MongoDB driver at point (3.1) and subscribing to the given Subscriber at point (3.3). As we may have noticed, FindPublisher exposes a fluent API that allows the building of an executable query using a functional programming style.
Along with the support of the Reactive Streams standard, the Reactive Streams-based MongoDB driver provides a simplified means for data querying. We will not go into detail about the implementation and behavior of that driver. Instead, we will cover this in Chapter 7, Reactive Database Access.