Search code examples
javaspring-webfluxreactive-programming

How do I modify the value of Mono in non-blocking fashion?


I am calling a third party library that returns value as type - Mono<String>. I have to modify the value of that string, lets say keep only the first 5 characters if the string is longer than that and return Mono<String> again. How do I implement this? I have tried to block the Mono to extract string value and then substring it but that violates reactive paradigm.

Mono<Stirng> myVal = getValueFromService();
Mono<String> myShortenedString = //???
return myShortenedString;

Solution

  • Mono is a monad, so you can either use map or flatMap to transform the value it contains.

    map is useful to transform the value using a "blocking" function. Example:

    Mono<String> myVal = Mono.just("test");
    Mono<String> truncated = myVal.map(value -> value.substring(1, 3));
    truncated.subscribe(System.out::println); // prints "es"
    

    flatMap is useful when the transforming function itself returns a Mono. It "flattens" the result, to return a Mono<T> instead of a Mono<Mono<T>>. Example:

    Mono<String> transform(String value) {
        return Mono.fromCallable(() -> value.substring(1, 3));
    }
    
    Mono<String> myVal = Mono.just("test");
    Mono<String> truncated = myVal.flatMap(value -> transform(value));
    truncated.subscribe(System.out::println); // prints "es"