Search code examples
monospring-webfluxflux

How to return Flux<String> in ServerResponse in WebFlux


I have a Jdbc Layer which is returning Flux. While returning the data, the fromPublisher method, it's accepting other Serializable classes, but the method is not accepting Flux.

Approach 1

public Mono<ServerResponse> getNames(final ServerRequest request) {
               Flux<String> strings = Flux.just("a", "b", "c"); 
        return ServerResponse.ok().contentType(APPLICATION_JSON)
                .body(fromPublisher(response), String.class);
    }

Above approach is returning abc combined as a Single String.

I tried this,

return ServerResponse.ok()
                .contentType(APPLICATION_JSON)
                .body(BodyInserters.fromValue(response), List.class);

I tried this aswell.

 Mono<List<String>> mono = response.collectList();
ServerResponse.ok()
                .contentType(APPLICATION_JSON)
                .body(fromPublisher(mono, String.class));

but this is also giving a Runtime error of

> body' should be an object, for reactive types use a variant specifying
> a publisher/producer and its related element type

enter image description here


Solution

  • This is working.

    Mono<List<String>> strings = Flux.just("a", "b", "c").collectList();
     
    return strings.flatMap(string -> ServerResponse.ok()
                            .contentType(APPLICATION_JSON)
                            .bodyValue(string));