No instance(s) of type variable(s) T exist so that Mono<T> conforms to ByteArrayResource

Viewed 282

I'm using the SpringWebflux to retrieve a ByteArrayResource from the request, but I want to store that ByteArray on an Optional.

I'm validating the status code, and if it was NOT_FOUND I retrieve a Mono with an Empty Optional. Otherwise, I want to get my response

This is my request:

 Supplier<Optional<ByteArrayResource>> requestSupplier =
                () ->
                         webClient
                               .get()
                               .uri(URL)
                        .accept(MediaType.APPLICATION_OCTET_STREAM)
.<Optional<ByteArrayResource>>exchangeToMono(
       response -> {
          if (response.statusCode().equals(HttpStatus.NOT_FOUND)) {
            return Mono.just(Optional.empty());
          }
           return Mono.just(
                 Optional.of(
                   response.bodyToMono(ByteArrayResource.class)));
.block();

And this has the following compile error: no instance(s) of type variable(s) T exist so that Mono conforms to ByteArrayResource

1 Answers

Mono.just(Optional.of(response.bodyToMono(ByteArrayResource.class))) doesn't give you a Mono<Optional<ByteArrayResource>>, it gives you a Mono<Optional<Mono<ByteArrayResource>>>. That's why you get the error, but the types clearly don't match.

Instead, you probably want something like:

return response.bodyToMono(ByteArrayResource.class).map(Optional::of);

...which will take your resource, and map it to an Optional while staying within the context of a Mono publisher.

Related