3

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

3
  • Flux is a stream not a list, so if you want to return a stream just return the flux directly, or remove the ”fromPublisher”. If you want to return a list you do a collectList on the flux and place the resulting Mono straight into the body Commented Jan 6, 2022 at 11:25
  • I tried that aswell. Its still giving me an error. Commented Jan 6, 2022 at 12:01
  • Please dont say ”i tried that aswell” tried what? All i pointed out? I dont see all your trials i pointed out in the question above. Also, dont say ”its still giving me an error” what error? We cant help you if you dont show us what you do what you get. If you expect help then please put in some effort Commented Jan 6, 2022 at 13:21

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

This is not returning as a list, Its returning abc as single string in the response body.
you didn't ask to return it as a list in your question. You asked to return a Flux<String> and this is how you do it
Oh, Okay. I meant it as List of Strings. my Bad.
did you find the correct method? I also want to return it like ["a","b","c']
3

This is working.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.