Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Reactor Merge vs Concat

I´m playing with Spring reactor, and I cannot see any differences between concat and merge operator

Here's my example

    @Test
    public void merge() {
        Flux<String> flux1 = Flux.just("hello").doOnNext(value -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Flux<String> flux2 = Flux.just("reactive").doOnNext(value -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Flux<String> flux3 = Flux.just("world");
        Flux.merge(flux1, flux2, flux3)
                .map(String::toUpperCase)
                .subscribe(System.out::println);
    }

    @Test
    public void concat() {
        Flux<String> flux1 = Flux.just("hello").doOnNext(value -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Flux<String> flux2 = Flux.just("reactive").doOnNext(value -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Flux<String> flux3 = Flux.just("world");
        Flux.concat(flux1, flux2, flux3)
                .map(String::toUpperCase)
                .subscribe(System.out::println);    
}

Both behave exactly the same. Can someone explain the difference between the two operations?

like image 972
paul Avatar asked Jan 27 '18 17:01

paul


People also ask

What does flux concat do?

Concatenate all sources provided in an Iterable , forwarding elements emitted by the sources downstream. Concatenate all sources emitted as an onNext signal from a parent Publisher , forwarding elements emitted by the sources downstream.

What is the difference between mono and flux?

Mono is more relatable to the Optional class in Java since it contains 0 or 1 value, and Flux is more relatable to List since it can have N number of values.

What does flux zip do?

Flux has multiple options to combine publishers. One of them is the zip operator. Zip waits for each source to emit one element and combines these elements. The output emitted is a tuple with as many publishers wrapped inside the zip.


1 Answers

The essential difference between merge and concat is that in merge, both streams are live. In case of concat, first stream is terminated and then the other stream is concatenated to it.

Concat enter image description here


Merge enter image description here

like image 83
Amriteya Avatar answered Oct 06 '22 00:10

Amriteya