How to convert Future to Uni?

Viewed 787

I have a Java API that returns a Future instance. I need to convert it to a Uni. From the mutiny documentation, I see it is possible to convert a CompletionStage to Uni, but I couldn't find how to convert a standard Future to Uni.

Q: How to convert java.util.concurrent.Future to Uni?

I understand that I can warp it's get() call to Uni, but it would be blocking, isn't it?

1 Answers

The problem with Future is that it's a blocking API and, unlike CompletionStage, there is no way to chain a stream of operations.

However, Mutiny has a way to deal with blocking API:

Future future = ...;
Uni<Object> uni = Uni.createFrom()
    .item( () -> future.get() )
    .runSubscriptionOn( Infrastructure.getDefaultWorkerPool() );

UPDATE:

My answer will work for all blocking code but the correct answer is in the comments:

Uni.createFrom().future(future);

or

Uni.createFrom().future(() -> future))
Related