Reactive Programming with Mono and Flux Explained

In continuation to previous post https://bit.ly/4bsoGg0 Once you get basics of Reactive programming, it becomes more interesting as we delve into further details. Let's talk about further components which come from libraries like Project Reactor. There are something called Mono and Flux. Both are different types of Publishers supported in reactive programming. Understanding these is as simple as reading a line of code. With the concept of Mono and Flux, you deal with a stream of data and not just the static data itself. Lets break it with an example. When we are fetching a unique user from a database based on id, we use Mono. Mono deals with fetching at most one object (0 or 1) or an error. Flux can be used to fetch 0 to N number of items, like a list of active users from a database. Instead of going into more details and confusing you, let's talk about other buzz words we use in reactive programming. Operators: In reactive programming, we don't just "get" data. We transform it as it flows. There are different operators which can be used for transformation without those for-loops which we were bound to use in imperative Java. Map: For synchronous transformation, like changing the type of a variable on the fly. FlatMap: Used for asynchronous transformations, like performing a database call for every item in a Flux. Filter: Filter out only the data which meets a given criteria. Concept of Backpressure: A very critical concept which should be carefully used in reactive programming; otherwise, the situation could go worse than imperative programming. Backpressure is a concept where the consumer can send a signal to the producer like "Hey, slow down, I can only handle five items at a time right now." In this way, the system maintains its own balance and eventual crashing of an application can be prevented. A Simple Example: Look at the logic below. In older Java, you'd wait for the whole list. In Reactive, you handle it as it comes. The stream starts, filters out the "C++" hurdle, transforms the rest, and then finally prints them. No curly brace hurdles, no complex declarations. Trust me, once you start thinking in streams, going back to the old way feels like taking a step backward. It might take extra time to master the operators, but the ultimate satisfaction of building a non-blocking, resilient system is worth the effort.

  • No alternative text description for this image

Excellent explanation 👌

To view or add a comment, sign in

Explore content categories