Flux Vs Stream

Key difference

  • Flux is asynchronous
  • Stream is synchronous
  • Flux can be reconsume and subscribe by multiple consumers
  • Stream can be consumed only once

Example

Using Flux

public class App {
	public static void main() {
		Flux<String> flux =  Flux.fromIterable(List.of("Customer1", "Customer2", "Customer3"));
		
		flux.subscribe(s -> {  
		  System.out.println("s = " + s);  
		});  
		  
		flux.subscribe(s -> {  
		  System.out.println("a = " + s);  
		});
	}
}
s = Customer1
s = Customer2
s = Customer3
a = Customer1
a = Customer2
a = Customer3

Using Stream

public class App {
	public static void main() {
		Stream<String> stream = Stream.of("Customer1", "Customer2", "Customer3");
		stream.forEach(s -> System.out.println("stream = " + s));  
		stream.forEach(s -> System.out.println("stream2 = " + s));
		
	}
}
stream = Customer1
stream = Customer2
stream = Customer3
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.base/java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
	at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
	at reactive.programming.App.main(App.java:32)

It's gonna throw exception since the stream is closed (at terminal operation forEach)