Extract data from Flux

Flux is the Project Reactor‘s implementation of the Publisher interface. It can emit 0..n values. In this post, you will learn to extract data from Flux.

How to extract data from Flux in Java?

The simplest way to get data from Flux would be using the subscribe() method, which accepts a Consumer as an argument. We can obtain the value and print it, like in the following example:

Example

class ReactiveJavaTutorial {

  public static void main(String[] args) throws InterruptedException {

    Flux<String> flux = Flux.fromArray(new String[]{"data1", "data2", "data3"});

    flux.subscribe(System.out::println);

  }
}
Output: data1 data2 data3
 
Another way would be using the Reactive Streams operators like onNext, flatMap, etc.

In the below example, we are using the onNext() method to get data from Flux and print it.

class ReactiveJavaTutorial {

  public static void main(String[] args) throws InterruptedException {

    Flux<String> flux = Flux.fromArray(new String[]{"data1", "data2", "data3"});

    flux.doOnNext(System.out::println).subscribe();

  }
}
Output: data1 data2 data3
 
Note: We need to subscribe to the Publisher. Otherwise, nothing will happen. 
 
We have many other operators that we can use to read the values from Flux. In the upcoming lessons, we will cover the most used ones.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *