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

mutiny.zero.operators.Transform Maven / Gradle / Ivy

Go to download

Mutiny Zero is a minimal API for creating reactive-streams compliant publishers

There is a newer version: 1.1.1
Show newest version
package mutiny.zero.operators;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.Flow;
import java.util.function.Function;

/**
 * A {@link java.util.concurrent.Flow.Publisher} that transforms elements using a {@link Function}.
 *
 * @param  the input elements type
 * @param  the output elements type
 */
public class Transform implements Flow.Publisher {

    private final Flow.Publisher upstream;
    private final Function function;

    /**
     * Build a new transformation publisher.
     *
     * @param upstream the upstream publisher
     * @param function the transformation function, must not throw exceptions, must not return {@code null} values
     */
    public Transform(Flow.Publisher upstream, Function function) {
        this.upstream = requireNonNull(upstream, "The upstream cannot be null");
        this.function = requireNonNull(function, "The function cannot be null");
    }

    @Override
    public void subscribe(Flow.Subscriber subscriber) {
        requireNonNull(subscriber, "The subscriber cannot be null");
        Processor processor = new Processor();
        processor.subscribe(subscriber);
        upstream.subscribe(processor);
    }

    private class Processor extends ProcessorBase {

        @Override
        public void onNext(I item) {
            if (!cancelled()) {
                try {
                    O result = function.apply(item);
                    if (result == null) {
                        throw new NullPointerException("The function produced a null result for item " + item);
                    }
                    downstream().onNext(result);
                } catch (Throwable failure) {
                    cancel();
                    downstream().onError(failure);
                }
            }
        }
    }
}