Flux

Flux represents a reactive stream emitting 0 to n elements. The following snippet shows a simple Flux example:

    @Test
public void simpleFluxStream() {
Flux<String> stubFluxStream = Flux.just("Jane", "Joe");
stubFluxStream.subscribe(new SystemOutConsumer());
}

A couple of important things to note are as follows:

  • Flux<String> stubFluxStream = Flux.just("Jane", "Joe"): We are creating a Flux using the Flux.just method. It can create simple streams with hardcoded elements.
  • stubFluxStream.subscribe(new SystemOutConsumer()): We are registering an instance of SystemOutConsumer as a subscriber on Flux.

The output is shown in the following screenshot:

The following snippet shows a more complex example of a Flux with two subscribers:

    private static List<String> streamOfNames = 
Arrays.asList("Ranga", "Adam", "Joe", "Doe", "Jane");
@Test
public void fluxStreamWithDelay() throws InterruptedException {
Flux<String> stubFluxWithNames =
Flux.fromIterable(streamOfNames)
.delayElements(Duration.ofMillis(1000));
stubFluxWithNames.subscribe(new SystemOutConsumer());
stubFluxWithNames.subscribe(new WelcomeConsumer());
Thread.sleep(10000);
}

A few important things to note are as follows:

  • Flux.fromIterable(streamOfNames).delayElements(Duration.ofMillis(1000)): Creates a Flux from the specified list of strings. Elements are emitted at the specified delay of 1000 milliseconds.
  • stubFluxWithNames.subscribe(new SystemOutConsumer()) and stubFluxWithNames.subscribe(new WelcomeConsumer()): We are registering two subscribers on Flux.
  • Thread.sleep(10000): Similar to the first Mono example, we introduce sleep to make the program wait until all elements from the Flux are emitted.

The output is shown in the following screenshot:

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

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