Paul Stoner
Paul Stoner

Reputation: 1512

Mutiny Uni Convert to Primitive Type

Up until now I have done very basic things with smallrye Mutiny in Quarkus. Basically, I have one or two very small web services which only interact with a web application. These services return a Uni<Response>.

Now I'm writing a logging service I want my others to pass information to. In this logging service, I need to return a value to calling services. The logging service will return this value as a Uni<Integer>. What I'm struggling with is how to extract the return value in the calling service as an int.

Here is the function in the logging service

    @GET
    @Path("/requestid")
    @Produces(MediaType.TEXT_PLAIN)
    public Uni<Integer> getMaxRequestId(){
        return service.getMaxRequestId();
    }

    public Uni<Integer> getMaxRequestId() {
        Integer result = Integer.valueOf(em.createQuery("select MAX(request_id) from service_requests").getFirstResult());
        
        if(result == null) {
            result = 0;
        }
        return Uni.createFrom().item(result += 1);
    }

And here is the client side code in the calling service

@Path("/requests")
public class RequestIdResource {
    
    @RestClient
    RequestIdServices service;
    
    @GET
    @Path("/requestid")
    @Produces(MediaType.TEXT_PLAIN)
    public Uni<Integer> getMaxRequestId(){
        return service.getMaxRequestId();
    }
}

    public void filter(ContainerRequestContext requestContext) throws IOException {

        int requestid = client.getMaxRequestId();

        rm.name = ConfigProvider.getConfig().getValue("quarkus.application.name", String.class);
        rm.server = requestContext.getUriInfo().getBaseUri().getHost();
        rm.text = requestContext.getUriInfo().getPath(true);
        rm.requestid = requestid;
        
    }

Basically everything I have tried creates another Uni. Maybe I am simply using the concept all wrong. But how do I get the Integer out of the Uni so I can get the intValue?

Upvotes: 3

Views: 6704

Answers (1)

Javier Toja
Javier Toja

Reputation: 1762

You need to invoke a terminal operation, or use the value and continue the chain.

If you want to invoke a terminal operator you can invoke the await operation to make your code blocking and wait for the response.

If you want to merge this reactive invocation with another that is present in your client code, you can join or combine your actual Mutiny stream with the on coming from the response by using the combine method.

If you just want to use the value and do not retrieve it, you can suscribe and get the result.

If you have a multi you can call directly the method toList

Assuming that you want to have some timeouts involved and you want to get the actual Integer, you can go with the await method and a timeout.

Upvotes: 5

Related Questions