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:
class SimpleServer {private final KitchenService kitchen;SimpleServer(KitchenService kitchen) { //1this.kitchen = kitchen;}Flux<Dish> doingMyJob() { //2return this.kitchen.getDishes().map(dish -> Dish.deliver(dish));//3}}
This SimpleServer class has the following features:
-
In line 5, whoever creates an instance of
SimpleServermust provide it with an instance ofKitchenService. This is known as constructor injection. -
In line 8, the
doingMyJob()function, which a manager can tap, invokes the kitchen togetDishes(). -
In line 10, after asking the
kitchenfordishes, it uses.map()to define a handler and tell them what to do with eachdishwhen it arrives. In this case, it invokes thedeliver(dish)function.
Note: The
deliver(dish)function of theDishclass sets thedish deliveredstate totrue.
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 ...