'compose() vs. transform() vs. as() vs. map() in Flux and Mono

Recently, I decided to try spring 5 with projectreactor.io (io.projectreactor:3.1.1).

Does anyone know what the best case of using this functions? What cons and pros of using each of them and where they should be used?

Good examples will be helpful.



Solution 1:[1]

I found the example in reference documentation little difficult to follow

So made the below programs to wrap my head around the tranform vs compose concept.

fnstatefull = flux -> {
                            Flux<String> f = flux.filter(color -> {
                                //only reds are allowed
                                return color.equalsIgnoreCase("red");   

                            });
                            //applies mapping 'toUpperCase' based on the external control 'toUpper'
                            if(toUpper) {
                                f= f.map(String::toUpperCase);
                            }
                            return f;
                        };

Transform

The operator is applied at the time of instantiation of the flux.

fnstatefull will behave same way for both subscribers below.

    Flux<String> f = Flux.just("red", "green", "blue");
    toUpper = false;
    f = f.transform(fnstatefull);
    toUpper = true;

    f.subscribe(op -> log.error("ONE>>>" + op));
    toUpper = false;
    f.subscribe(op -> log.error("TWO>>>" + op));

Output

ReactordemoApplication - ONE>>>red
ReactordemoApplication - TWO>>>red

Compose

The operator is applied at the time of subscription to the flux.

fnstatefull will behave differently for each subscriber below.

    Flux<String> f = Flux.just("red", "green", "blue");
    toUpper = false;
    f = f.compose(fnstatefull);
    toUpper = true;

    f.subscribe(op -> log.error("ONE>>>" + op));
    toUpper = false;
    f.subscribe(op -> log.error("TWO>>>" + op));

Output

ReactordemoApplication - ONE>>>RED
ReactordemoApplication - TWO>>>red

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1