Interaction with other reactive libraries

Despite the fact that WebFlux uses Project Reactor 3 as the central building block, WebFlux allows the use of other reactive libraries as well. To enable cross-library interoperability, most operations in WebFlux are based on interfaces from the Reactive Streams specification. In this way, we can easily replace code written in Reactor 3 with RxJava 2 or Akka Streams:

import io.reactivex.Observable;                                    // (1)
... //

@RestController // (2)
class AlbomsController { //
final ReactiveAdapterRegistry adapterRegistry; // (2.1)
... //

@GetMapping("/songs") // (3)
public Observable<Song> findAlbomByArtists( // (3.1)
Flux<Artist> artistsFlux // (3.2)
) {
Observable<Artist> observable = adapterRegistry // (4)
.getAdapter(Observable.class) //
.fromPublisher(artistsFlux); //
Observable<Song> albomsObservable = ...; // (4.1)
//
return albomsObservable; // (4.2)
}
}

This code is explained in the following list:

  1. This is the import declaration, which demonstrates that we import the Observable from RxJava 2.
  2. This is the AlbomsController class, which is annotated with the @RestController annotation. We also declare a field of the ReactiveAdapterRegistry type, which is used later in this example.
  3. Here, we have a declaration of the request handler method called findAlbumByArtists. As we can see, findAlbumByArtists accepts a Publisher of type Flux<Artist>, as shown at point (3.2), and returns Observable<Song>, as shown at point (3.1).
  4. Here, we have the declarations to map artistsFlux to Observable<Artist>,  execute business logic (at 4.1)and return the result to the caller.

The preceding example shows how reactive communication might be rewritten using reactive types from RxJava, along with the Project Reactor reactive types. As we may remember from Chapter 5, Going Reactive with Spring Boot 2, reactive type conversion is part of the Spring Core module and is supported by org.springframework.core.ReactiveAdapterRegistry and org.springframework.core.ReactiveAdapter. These classes allow conversion both to and from the Reactive Streams Publisher class. Hence, with that support library, we may use almost any reactive library without having to tightly couple it with Project Reactor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.119.106