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

io.vertx.reactivex.impl.FlowableReadStream Maven / Gradle / Ivy

There is a newer version: 5.0.0.CR3
Show newest version
package io.vertx.reactivex.impl;

import io.reactivex.Flowable;
import io.reactivex.FlowableSubscriber;
import io.reactivex.internal.subscriptions.BasicIntQueueSubscription;
import io.reactivex.internal.subscriptions.EmptySubscription;
import io.reactivex.processors.UnicastProcessor;
import io.vertx.core.streams.ReadStream;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

/**
 * @author Julien Viet
 */
public class FlowableReadStream extends Flowable {

  public static final long DEFAULT_MAX_BUFFER_SIZE = 256;

  private final ReadStream stream;
  private final Function f;
  private final AtomicReference current;

  public FlowableReadStream(ReadStream stream, long maxBufferSize, Function f) {

    stream.pause();

    this.stream = stream;
    this.f = f;
    this.current = new AtomicReference<>();
  }

  private void release() {
    Subscription sub = current.get();
    if (sub != null) {
      if (current.compareAndSet(sub, null)) {
        try {
          stream.exceptionHandler(null);
          stream.endHandler(null);
          stream.handler(null);
        } catch (Exception ignore) {
        } finally {
          try {
            stream.resume();
          } catch (Exception ignore) {
          }
        }
      }
    }
  }

  @Override
  protected void subscribeActual(Subscriber subscriber) {

    Subscription sub = new Subscription() {
      @Override
      public void request(long l) {
        if (current.get() == this) {
          stream.fetch(l);
        }
      }

      @Override
      public void cancel() {
        release();
      }
    };
    if (!current.compareAndSet(null, sub)) {
      EmptySubscription.error(new IllegalStateException("This processor allows only a single Subscriber"), subscriber);
      return;
    }

    stream.pause();

    stream.endHandler(v -> {
      release();
      subscriber.onComplete();
    });
    stream.exceptionHandler(err -> {
      release();
      subscriber.onError(err);
    });
    stream.handler(item -> {
      subscriber.onNext(f.apply(item));
    });

    subscriber.onSubscribe(sub);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy