Welcome to our deep dive into Java's Reactive Programming! Today, we'll learn about two fundamental concepts: Mono and Flux. These are essential components of Project Reactor, a powerful library for building reactive applications.
Mono<T> represents a sequence containing either a single item of type T or an empty sequence. It's a way to handle a single data item or an error, making it ideal for methods that are expected to return a single item or an exception.
You can create a Mono instance in several ways. Here's an example of creating a Mono from a T value:
Mono<String> mono = Mono.just("Hello World!");Suppose you're developing a simple web application, and you want to read a user's profile from a database. If the user exists, you return their profile; otherwise, you throw an exception. This is perfect for using Mono.
Mono<User> getUserProfile(String username) {
// Database query to fetch user profile
// Return the User object if found, otherwise throw an exception
}Flux<T> represents a sequence of 0 or more items of type T. It's primarily used when you expect to handle multiple items or an empty sequence.
Creating a Flux instance is similar to creating a Mono. Here's an example of creating a Flux from an array of String values:
Flux<String> flux = Flux.fromArray(new String[]{"One", "Two", "Three"});Let's consider a scenario where you're developing a chat application. Each user can send multiple messages. Here, you can use Flux to manage these messages.
Flux<Message> getUserMessages(String username) {
// Database query to fetch messages for the user
// Return a `Flux` of messages
}Both Mono and Flux support a set of operators and helper methods to perform various operations, like mapping, filtering, and combining sequences.
map: Apply a given function to each item in a sequencefilter: Retain only items that satisfy a given predicateflatMap: Transform each item into a sequence and concatenate the resulting sequencesswitchIfEmpty: If the sequence is empty, use the provided publisher insteadLet's take the example of the chat application and apply some operators to filter or map the messages.
Flux<Message> getUserMessages(String username) {
// Database query to fetch messages for the user
// Return a `Flux` of messages
}
Flux<Message> filterMessagesByRecipient(Flux<Message> messages, String recipient) {
return messages.filter(message -> message.getRecipient().equals(recipient));
}
Flux<String> mapMessagesToContent(Flux<Message> messages) {
return messages.map(Message::getContent);
}Happy learning, and see you in the next lesson! 🚀