Shiva kumar
Shiva kumar

Reputation: 732

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

Upvotes: 3

Views: 7507

Answers (2)

Shiva kumar
Shiva kumar

Reputation: 732

This is working.

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

Upvotes: 3

Michael McFadyen
Michael McFadyen

Reputation: 3005

Below is an example of how to send back a Flux<String> in the body of a response

Flux<String> strings = Flux.just("a", "b", "c");
ServerResponse.ok().body(strings, String.class);

Upvotes: 3

Related Questions