package reactor.adapter;
import java.util.concurrent.Flow;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Scannable;
import reactor.core.publisher.Flux;
@SuppressWarnings("Since15")
public abstract class JdkFlowAdapter {
public static <T> Flow.Publisher<T> publisherToFlowPublisher(final Publisher<T>
publisher) {
return new PublisherAsFlowPublisher<>(publisher);
}
public static <T> Flux<T> flowPublisherToFlux(Flow.Publisher<T> publisher) {
return new FlowPublisherAsFlux<>(publisher);
}
private static class FlowPublisherAsFlux<T> extends Flux<T> implements Scannable {
private final java.util.concurrent.Flow.Publisher<T> pub;
private FlowPublisherAsFlux(java.util.concurrent.Flow.Publisher<T> pub) {
this.pub = pub;
}
@Override
public void subscribe(final CoreSubscriber<? super T> actual) {
pub.subscribe(new SubscriberToRS<>(actual));
}
@Override
public Object scanUnsafe(Attr key) {
return null;
}
}
private static class PublisherAsFlowPublisher<T> implements Flow.Publisher<T> {
private final Publisher<T> pub;
private PublisherAsFlowPublisher(Publisher<T> pub) {
this.pub = pub;
}
@Override
public void subscribe(Flow.Subscriber<? super T> subscriber) {
pub.subscribe(new FlowSubscriber<>(subscriber));
}
}
private static class FlowSubscriber<T> implements CoreSubscriber<T>, Flow.Subscription {
private final Flow.Subscriber<? super T> subscriber;
Subscription subscription;
public FlowSubscriber(Flow.Subscriber<? super T> subscriber) {
this.subscriber = subscriber;
}
@Override
public void onSubscribe(final Subscription s) {
this.subscription = s;
subscriber.onSubscribe(this);
}
@Override
public void onNext(T o) {
subscriber.onNext(o);
}
@Override
public void onError(Throwable t) {
subscriber.onError(t);
}
@Override
public void onComplete() {
subscriber.onComplete();
}
@Override
public void request(long n) {
subscription.request(n);
}
@Override
public void cancel() {
subscription.cancel();
}
}
private static class SubscriberToRS<T> implements Flow.Subscriber<T>, Subscription {
private final Subscriber<? super T> s;
Flow.Subscription subscription;
public SubscriberToRS(Subscriber<? super T> s) {
this.s = s;
}
@Override
public void onSubscribe(final Flow.Subscription subscription) {
this.subscription = subscription;
s.onSubscribe(this);
}
@Override
public void onNext(T o) {
s.onNext(o);
}
@Override
public void onError(Throwable throwable) {
s.onError(throwable);
}
@Override
public void onComplete() {
s.onComplete();
}
@Override
public void request(long n) {
subscription.request(n);
}
@Override
public void cancel() {
subscription.cancel();
}
}
JdkFlowAdapter(){}
}