Close

Reactor - Creating Flux and Mono with empty()

[Last Updated: Sep 27, 2020]

Following are empty() methods of Flux and Mono to create their empty instances which complete without emitting any item.

Flux method

public static <T> Flux<T> empty()

Mono method

public static <T> Mono<T> empty()

Examples

package com.logicbig.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class FluxMonoJustExamples {
  public static void main(String[] args) {
      System.out.println("-- Flux#empty example --");
      Flux.empty()
          .subscribe(System.out::println);

      System.out.println("-- Mono#empty example --");
      Mono.empty()
          .subscribe(System.out::println);
  }
}
-- Flux#empty example --
-- Mono#empty example --

Since Flux/Mono don't allow null items, Flux#empty() and Mono#empty() can be useful where we need to handle null situation, examples:

package com.logicbig.example;

import reactor.core.publisher.Flux;

public class FluxEmptyExample1 {

  public static void main(String[] args) {
      if (args.length != 0) {
          process(Flux.just(args[0]));
      } else {
          process(Flux.empty());
      }
  }

  private static void process(Flux<String> flux) {
      flux.map(n -> n.length())
          .subscribe(System.out::println);
  }
}
package com.logicbig.example;

import reactor.core.publisher.Flux;

public class FluxEmptyExample2 {

  public static void main(String[] args) {
      process(args.length != 0 ? args[0] : null)
              .subscribe(System.out::println);
  }

  private static Flux<Integer> process(String i) {
      if (i == null) {
          return Flux.empty();
      } else {
          return Flux.just(i)
                     .map(String::length);
      }
  }
}

Example Project

Dependencies and Technologies Used:

  • reactor-core 3.3.10.RELEASE: Non-Blocking Reactive Foundation for the JVM.
  • JDK 8
  • Maven 3.5.4

Flux#empty() and Mono#empty() examples Select All Download
  • reactor-create-with-empty-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • FluxMonoJustExamples.java

    See Also