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

net.pincette.rs.Probe Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
package net.pincette.rs;

import static net.pincette.util.Util.tryToDo;

import java.util.concurrent.Flow.Processor;
import java.util.function.Consumer;

/**
 * The processor lets all values through. It calls the given functions when more values are
 * requested or are emitted, which allows you to probe the backpressure mechanism.
 *
 * @param  the value type.
 * @author Werner Donn\u00e9
 * @since 3.0
 */
public class Probe extends ProcessorBase {
  private final Runnable complete;
  private final Consumer error;
  private final Consumer more;
  private final Consumer value;

  public Probe(final Consumer more) {
    this(more, v -> {});
  }

  public Probe(final Consumer more, final Consumer value) {
    this(more, value, () -> {});
  }

  public Probe(final Consumer more, final Consumer value, final Runnable complete) {
    this(more, value, complete, t -> {});
  }

  public Probe(
      final Consumer more,
      final Consumer value,
      final Runnable complete,
      final Consumer error) {
    this.more = more;
    this.value = value;
    this.complete = complete;
    this.error = error;
  }

  public Probe(final Runnable complete) {
    this(n -> {}, v -> {}, complete);
  }

  public static  Processor probe(final Consumer more) {
    return new Probe<>(more);
  }

  public static  Processor probe(final Consumer more, final Consumer value) {
    return new Probe<>(more, value);
  }

  public static  Processor probe(
      final Consumer more, final Consumer value, final Runnable complete) {
    return new Probe<>(more, value, complete);
  }

  public static  Processor probe(
      final Consumer more,
      final Consumer value,
      final Runnable complete,
      final Consumer error) {
    return new Probe<>(more, value, complete, error);
  }

  public static  Processor probe(final Runnable complete) {
    return new Probe<>(complete);
  }

  @Override
  protected void emit(final long number) {
    tryToDo(
        () -> {
          if (more != null) {
            more.accept(number);
          }

          subscription.request(number);
        },
        this::onError);
  }

  @Override
  public void onComplete() {
    tryToDo(
        () -> {
          if (complete != null) {
            complete.run();
          }

          super.onComplete();
        },
        this::onError);
  }

  @Override
  public void onError(final Throwable t) {
    if (error != null) {
      error.accept(t);
    }

    super.onError(t);
  }

  @Override
  public void onNext(final T item) {
    tryToDo(
        () -> {
          if (value != null) {
            value.accept(item);
          }

          subscriber.onNext(item);
        },
        this::onError);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy