package reactor.core.publisher;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.reactivestreams.Publisher;
import reactor.core.CoreSubscriber;
final class FluxConcatIterable<T> extends Flux<T> implements SourceProducer<T> {
final Iterable<? extends Publisher<? extends T>> iterable;
FluxConcatIterable(Iterable<? extends Publisher<? extends T>> iterable) {
this.iterable = Objects.requireNonNull(iterable, "iterable");
}
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
Iterator<? extends Publisher<? extends T>> it;
try {
it = Objects.requireNonNull(iterable.iterator(),
"The Iterator returned is null");
}
catch (Throwable e) {
Operators.error(actual, Operators.onOperatorError(e, actual.currentContext()));
return;
}
ConcatIterableSubscriber<T> parent = new ConcatIterableSubscriber<>(actual, it);
actual.onSubscribe(parent);
if (!parent.isCancelled()) {
parent.onComplete();
}
}
@Override
public Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
static final class ConcatIterableSubscriber<T>
extends Operators.MultiSubscriptionSubscriber<T, T> {
final Iterator<? extends Publisher<? extends T>> it;
volatile int wip;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<ConcatIterableSubscriber> WIP =
AtomicIntegerFieldUpdater.newUpdater(ConcatIterableSubscriber.class,
"wip");
long produced;
ConcatIterableSubscriber(CoreSubscriber<? super T> actual,
Iterator<? extends Publisher<? extends T>> it) {
super(actual);
this.it = it;
}
@Override
public void onNext(T t) {
produced++;
actual.onNext(t);
}
@Override
public void onComplete() {
if (WIP.getAndIncrement(this) == 0) {
Iterator<? extends Publisher<? extends T>> a = this.it;
do {
if (isCancelled()) {
return;
}
boolean b;
try {
b = a.hasNext();
}
catch (Throwable e) {
onError(Operators.onOperatorError(this, e,
actual.currentContext()));
return;
}
if (isCancelled()) {
return;
}
if (!b) {
actual.onComplete();
return;
}
Publisher<? extends T> p;
try {
p = Objects.requireNonNull(it.next(),
"The Publisher returned by the iterator is null");
}
catch (Throwable e) {
actual.onError(Operators.onOperatorError(this, e,
actual.currentContext()));
return;
}
if (isCancelled()) {
return;
}
long c = produced;
if (c != 0L) {
produced = 0L;
produced(c);
}
p.subscribe(this);
if (isCancelled()) {
return;
}
}
while (WIP.decrementAndGet(this) != 0);
}
}
@Override
public Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
}
}