mutiny.zero.operators.Transform Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mutiny-zero Show documentation
Show all versions of mutiny-zero Show documentation
Mutiny Zero is a minimal API for creating reactive-streams compliant publishers
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 super O> 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);
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy