Reactive Programming in Java: How, Why, and Is It Worth Doing?. Implementations
Letís consider the existing implementations of reactive streams:
- RxJava. This library is implemented for various languages. Besides RxJava, there are also Rx for C#, JS, Kotlin, Scala, etc.
- Reactor Core. It was created under Spring and included in Spring 5
- Akka streams from Martin Odersky, creator of Scala. They created an Akka framework (approach with Actor), and Akka streams are an implementation of reactive streams which are on friendly grounds with that framework
These implementations are much alike; they all implement Java 9 reactive streams specification.
Letís take a closer look at Spring Reactor.
Letís summarize what a function can return:
An ordinary function returns one value and does that in sync.
If we use Java 8, we can return a data stream from a function. When many values have been returned, they can be sent to processing. But we cannot send data to processing before they have been received ó Streams work only in sync.
Here we are already using an asynchronous approach, but the function returns only one value:
- either CompletableFuture (Java) and then after some time, an asynchronous response arrives
- or Mono that returns one value in the Spring Reactor library
And here, we have reactive streams. They are asynchronous, i.e., they return values not at once but after some time. It is in that option that you can get a stream of values, which will be extended in time. So we combine the benefits of Streams, enabling us to return a chain of values and asynchronicity that allows us to postpone the return of values.
For example, you are reading a file, and it is changing. In the case of Single/Asynchronous, you get the whole file after some time. In the case of Multiple/Asynchronous, you get a data stream from the file, which you can start processing immediately. You can simultaneously read data, process it, and, possibly, write it somewhere. Reactive asynchronous streams are called:
- Publisher (in Java 9 spec);
- Observable (in RxJava);
- Flux (in Spring Reactor).
Interested in learning how to program with Java or in upgrading your Java programming skills? Check out our trainings