package reactor.core.publisher;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.function.BooleanSupplier;
import org.reactivestreams.Publisher;
import reactor.core.CoreSubscriber;
final class FluxRepeatPredicate<T> extends FluxOperator<T, T> {
final BooleanSupplier predicate;
FluxRepeatPredicate(Flux<? extends T> source, BooleanSupplier predicate) {
super(source);
this.predicate = Objects.requireNonNull(predicate, "predicate");
}
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
RepeatPredicateSubscriber<T> parent = new RepeatPredicateSubscriber<>(source,
actual, predicate);
actual.onSubscribe(parent);
if (!parent.isCancelled()) {
parent.resubscribe();
}
}
static final class RepeatPredicateSubscriber<T>
extends Operators.MultiSubscriptionSubscriber<T, T> {
final Publisher<? extends T> source;
final BooleanSupplier predicate;
volatile int wip;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<RepeatPredicateSubscriber> WIP =
AtomicIntegerFieldUpdater.newUpdater(RepeatPredicateSubscriber.class, "wip");
long produced;
RepeatPredicateSubscriber(Publisher<? extends T> source,
CoreSubscriber<? super T> actual, BooleanSupplier predicate) {
super(actual);
this.source = source;
this.predicate = predicate;
}
@Override
public void onNext(T t) {
produced++;
actual.onNext(t);
}
@Override
public void onComplete() {
boolean b;
try {
b = predicate.getAsBoolean();
} catch (Throwable e) {
actual.onError(Operators.onOperatorError(e, actual.currentContext()));
return;
}
if (b) {
resubscribe();
} else {
actual.onComplete();
}
}
void resubscribe() {
if (WIP.getAndIncrement(this) == 0) {
do {
if (isCancelled()) {
return;
}
long c = produced;
if (c != 0L) {
produced = 0L;
produced(c);
}
source.subscribe(this);
} while (WIP.decrementAndGet(this) != 0);
}
}
}
}