The Server in Reactive Programming

Learn about the role of a server in reactive programming.

We'll cover the following...

To focus on the concept of a server delivering those asynchronous dishes we studied, let’s write some more code!

A SimpleServer

Let’s take a look at the code for the SimpleServer class below:

Press + to interact
KitchenService.java
SimpleServer.java
Dish.java
class SimpleServer {
private final KitchenService kitchen;
SimpleServer(KitchenService kitchen) { //1
this.kitchen = kitchen;
}
Flux<Dish> doingMyJob() { //2
return this.kitchen.getDishes()
.map(dish -> Dish.deliver(dish));//3
}
}

This SimpleServer class has the following features:

  1. In line 5, whoever creates an instance of SimpleServer must provide it with an instance of KitchenService. This is known as constructor injection.

  2. In line 8, the doingMyJob() function, which a manager can tap, invokes the kitchen to getDishes().

  3. In line 10, after asking the kitchen for dishes, it uses .map() to define a handler and tell them what to do with each dish when it arrives. In this case, it invokes the deliver(dish) function.

Note: The deliver(dish) function of the Dish class sets the dish delivered state to true.

With this code, we’ve defined a simple reactive consumer. It invokes another reactive service and transforms the results.

Look closely and notice that, while retrieving a Flux of Dish objects from the kitchen, it returns the same type. The difference is that the kitchen produces a cooked series of entrées, while the SimpleServer produces a delivered series of entrées.

We are using a Java 8 lambda function dish → Dish.deliver(dish) in the code ...