All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.smallrye.mutiny.vertx.UniHelper Maven / Gradle / Ivy

There is a newer version: 3.17.1
Show newest version
package io.smallrye.mutiny.vertx;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

import io.smallrye.mutiny.Uni;
import io.smallrye.mutiny.subscription.UniSubscriber;
import io.smallrye.mutiny.subscription.UniSubscription;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;

public class UniHelper {

    @SuppressWarnings({ "rawtypes", "Convert2Lambda" })
    public static Consumer NOOP = new Consumer() {
        @Override
        public void accept(Object o) {
            // Do nothing
        }
    };

    /**
     * Returns a {@link Uni} that, when subscribed, uses the provided {@code handler} to adapt a callback-based
     * asynchronous method.
     * 

* For example: * *

     * {
     *     @code
     *     io.vertx.core.Vertx vertx = Vertx.vertx();
     *     Uni blockingMethodResult = UniHelper
     *             .toMaybe(handler -> vertx. executeBlocking(fut -> fut.complete(invokeBlocking()), handler));
     * }
     * 
*

* This is useful when using Mutiny without the Vert.x Mutiny API or your own asynchronous methods. * * @param handler the code executed when the returned {@link Uni} is subscribed. * @return the uni */ public static Uni toUni(Consumer>> handler) { return AsyncResultUni.toUni(handler); } /** * Adapts an {@code Uni} to a Vert.x {@link Future}. *

* The single will be immediately subscribed and the returned future will * be updated with the result of the single. * * @param single the single to adapt * @return the future */ public static Future toFuture(Uni single) { Promise promise = Promise.promise(); single.subscribe().with(promise::complete, promise::fail); return promise.future(); } public static Uni toUni(Future future) { return Uni.createFrom().completionStage(future.toCompletionStage()); } /** * Adapts an Vert.x {@code Handler>} to an {@link io.smallrye.mutiny.subscription.UniSubscriber}. *

* The returned observer can be subscribed to an {@link Uni#subscribe()}. * * @param handler the handler to adapt * @return the observer */ public static UniSubscriber toSubscriber(Handler> handler) { AtomicBoolean terminated = new AtomicBoolean(); return new UniSubscriber() { @Override public void onSubscribe(UniSubscription subscription) { // ignore it. } @Override public void onItem(T item) { if (terminated.compareAndSet(false, true)) { handler.handle(Future.succeededFuture(item)); } } @Override public void onFailure(Throwable failure) { if (terminated.compareAndSet(false, true)) { handler.handle(Future.failedFuture(failure)); } } }; } }