Compose () vs. transform () vs. as () vs. map () in Flux and Mono

I recently decided to try version 5 with projectreactor.io (io.projectreactor: 3.1.1).

Does anyone know how best to use this feature? What are the pros and cons of using each of them and where should they be used?

Good examples will be helpful.

+9
source share
2 answers

Here you have two different categories of operators:

Operators who work with most Flux

transformand composeare intended for data exchange

, , , compose transform.

, : transform , compose ( ).

. .

as

Function Flux, . Mono ( javadoc), , factory.

reactor-addons MathFlux, , :

MathFlux.sumInt(Flux.range(1, 10)
                    .map(i -> i + 2)
                    .map(i -> i * 10))
        .map(isum -> "sum=" + isum);

To:

Flux.range(1, 10)
    .map(i -> i + 2)
    .map(i -> i * 10)
    .as(MathFlux::sumInt)
    .map(isum -> "sum=" + isum)

( , , Kotlin, Java :))

, , Flux

map - . 1-1 , .

MathFlux map 2 , 10, String .

+15

, tranform vs compose.

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

.

fnstatefull .

    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));

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

.

fnstatefull - .

    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));

ReactordemoApplication - ONE>>>red
ReactordemoApplication - TWO>>>red
+2

Source: https://habr.com/ru/post/1689445/


All Articles