Convert Mono to Flux and vice versa

In this post, you will learn to convert Mono to Flux and vice versa.

Convert Mono to Flux in Java

To create a Flux from Mono, you can use the overloaded method from(), which accepts a Publisher as an argument. In this case, we will pass Mono.

Example

class ReactiveJavaTutorial {

  public static void main(String[] args) {

    Mono<String> mono = Mono.just("data");

    Flux<String> fluxFromMono = Flux.from(mono);

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

  }
}
Output: data

Convert Flux to Mono

You can use the next() method to convert Flux to Mono. If Flux has more than one value, the newly created Mono will contain the first value.

Example

class ReactiveJavaTutorial {

  public static void main(String[] args) {

    // one value
    Flux<String> flux1 = Flux.just("data1");

    Mono<String> monoFromFlux1 = flux1.next();

    // get data from mono
    monoFromFlux1.subscribe(data -> System.out.println("monoFromFlux1 data: " + data));

    // multiple values
    Flux<String> flux2 = Flux.just("data2", "data3", "data4");

    Mono<String> monoFromFlux2 = flux2.next();

    // get data from mono
    monoFromFlux2.subscribe(data -> System.out.println("monoFromFlux2 data: " + data));

  }
}
Output: monoFromFlux1 data: data1 monoFromFlux2 data: data2
 
That’s it!

Leave a Reply

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