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

io.reactivex.flowable.internal.operators.FlowablePublishMulticast Maven / Gradle / Ivy

The newest version!
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.reactivex.flowable.internal.operators;

import java.util.concurrent.atomic.*;

import org.reactivestreams.*;

import hu.akarnokd.reactivestreams.extensions.*;
import io.reactivex.common.*;
import io.reactivex.common.exceptions.*;
import io.reactivex.common.functions.Function;
import io.reactivex.common.internal.functions.ObjectHelper;
import io.reactivex.flowable.Flowable;
import io.reactivex.flowable.internal.subscriptions.*;
import io.reactivex.flowable.internal.utils.*;

/**
 * Multicasts a Flowable over a selector function.
 *
 * @param  the input value type
 * @param  the output value type
 */
public final class FlowablePublishMulticast extends AbstractFlowableWithUpstream {

    final Function, ? extends Publisher> selector;

    final int prefetch;

    final boolean delayError;

    public FlowablePublishMulticast(Flowable source,
            Function, ? extends Publisher> selector, int prefetch,
            boolean delayError) {
        super(source);
        this.selector = selector;
        this.prefetch = prefetch;
        this.delayError = delayError;
    }

    @Override
    protected void subscribeActual(Subscriber s) {
        MulticastProcessor mp = new MulticastProcessor(prefetch, delayError);

        Publisher other;

        try {
            other = ObjectHelper.requireNonNull(selector.apply(mp), "selector returned a null Publisher");
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            EmptySubscription.error(ex, s);
            return;
        }

        OutputCanceller out = new OutputCanceller(s, mp);

        other.subscribe(out);

        source.subscribe(mp);
    }

    static final class OutputCanceller implements RelaxedSubscriber, Subscription {
        final Subscriber actual;

        final MulticastProcessor processor;

        Subscription s;

        OutputCanceller(Subscriber actual, MulticastProcessor processor) {
            this.actual = actual;
            this.processor = processor;
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.s, s)) {
                this.s = s;

                actual.onSubscribe(this);
            }
        }

        @Override
        public void onNext(R t) {
            actual.onNext(t);
        }

        @Override
        public void onError(Throwable t) {
            actual.onError(t);
            processor.dispose();
        }

        @Override
        public void onComplete() {
            actual.onComplete();
            processor.dispose();
        }

        @Override
        public void request(long n) {
            s.request(n);
        }

        @Override
        public void cancel() {
            s.cancel();
            processor.dispose();
        }
    }

    static final class MulticastProcessor extends Flowable implements RelaxedSubscriber, Disposable {

        @SuppressWarnings("rawtypes")
        static final MulticastSubscription[] EMPTY = new MulticastSubscription[0];

        @SuppressWarnings("rawtypes")
        static final MulticastSubscription[] TERMINATED = new MulticastSubscription[0];

        final AtomicInteger wip;

        final AtomicReference[]> subscribers;

        final int prefetch;

        final int limit;

        final boolean delayError;

        final AtomicReference s;

        volatile FusedQueue queue;

        int sourceMode;

        volatile boolean done;
        Throwable error;

        int consumed;

        @SuppressWarnings("unchecked")
        MulticastProcessor(int prefetch, boolean delayError) {
            this.prefetch = prefetch;
            this.limit = prefetch - (prefetch >> 2); // request after 75% consumption
            this.delayError = delayError;
            this.wip = new AtomicInteger();
            this.s = new AtomicReference();
            this.subscribers = new AtomicReference[]>(EMPTY);
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.setOnce(this.s, s)) {
                if (s instanceof FusedQueueSubscription) {
                    @SuppressWarnings("unchecked")
                    FusedQueueSubscription qs = (FusedQueueSubscription) s;

                    int m = qs.requestFusion(FusedQueueSubscription.ANY);
                    if (m == FusedQueueSubscription.SYNC) {
                        sourceMode = m;
                        queue = qs;
                        done = true;
                        drain();
                        return;
                    }
                    if (m == FusedQueueSubscription.ASYNC) {
                        sourceMode = m;
                        queue = qs;
                        QueueDrainHelper.request(s, prefetch);
                        return;
                    }
                }

                queue = QueueDrainHelper.createQueue(prefetch);

                QueueDrainHelper.request(s, prefetch);
            }
        }

        @Override
        public void dispose() {
            SubscriptionHelper.cancel(s);
            if (wip.getAndIncrement() == 0) {
                FusedQueue q = queue;
                if (q != null) {
                    q.clear();
                }
            }
        }

        @Override
        public boolean isDisposed() {
            return SubscriptionHelper.isCancelled(s.get());
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            if (sourceMode == FusedQueueSubscription.NONE && !queue.offer(t)) {
                s.get().cancel();
                onError(new MissingBackpressureException());
                return;
            }
            drain();
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaCommonPlugins.onError(t);
                return;
            }
            error = t;
            done = true;
            drain();
        }

        @Override
        public void onComplete() {
            if (!done) {
                done = true;
                drain();
            }
        }

        boolean add(MulticastSubscription s) {
            for (;;) {
                MulticastSubscription[] current = subscribers.get();
                if (current == TERMINATED) {
                    return false;
                }
                int n = current.length;
                @SuppressWarnings("unchecked")
                MulticastSubscription[] next = new MulticastSubscription[n + 1];
                System.arraycopy(current, 0, next, 0, n);
                next[n] = s;
                if (subscribers.compareAndSet(current, next)) {
                    return true;
                }
            }
        }

        @SuppressWarnings("unchecked")
        void remove(MulticastSubscription s) {
            for (;;) {
                MulticastSubscription[] current = subscribers.get();
                if (current == TERMINATED || current == EMPTY) {
                    return;
                }
                int n = current.length;
                int j = -1;

                for (int i = 0; i < n; i++) {
                    if (current[i] == s) {
                        j = i;
                        break;
                    }
                }

                if (j < 0) {
                    return;
                }
                MulticastSubscription[] next;
                if (n == 1) {
                    next = EMPTY;
                } else {
                    next = new MulticastSubscription[n - 1];
                    System.arraycopy(current, 0, next, 0, j);
                    System.arraycopy(current, j + 1, next, j, n - j - 1);
                }
                if (subscribers.compareAndSet(current, next)) {
                    return;
                }
            }
        }

        @Override
        protected void subscribeActual(Subscriber s) {
            MulticastSubscription ms = new MulticastSubscription(s, this);
            s.onSubscribe(ms);
            if (add(ms)) {
                if (ms.isCancelled()) {
                    remove(ms);
                    return;
                }
                drain();
            } else {
                Throwable ex = error;
                if (ex != null) {
                    s.onError(ex);
                } else {
                    s.onComplete();
                }
            }
        }

        void drain() {
            if (wip.getAndIncrement() != 0) {
                return;
            }

            int missed = 1;

            FusedQueue q = queue;

            int upstreamConsumed = consumed;
            int localLimit = limit;
            boolean canRequest = sourceMode != FusedQueueSubscription.SYNC;

            for (;;) {
                MulticastSubscription[] array = subscribers.get();

                int n = array.length;

                if (q != null && n != 0) {
                    long r = Long.MAX_VALUE;

                    for (MulticastSubscription ms : array) {
                        long u = ms.get();
                        if (u != Long.MIN_VALUE) {
                            if (r > u) {
                                r = u;
                            }
                        }
                    }

                    long e = 0L;
                    while (e != r) {
                        if (isDisposed()) {
                            q.clear();
                            return;
                        }

                        boolean d = done;

                        if (d && !delayError) {
                            Throwable ex = error;
                            if (ex != null) {
                                errorAll(ex);
                                return;
                            }
                        }

                        T v;

                        try {
                            v = q.poll();
                        } catch (Throwable ex) {
                            Exceptions.throwIfFatal(ex);
                            SubscriptionHelper.cancel(s);
                            errorAll(ex);
                            return;
                        }

                        boolean empty = v == null;

                        if (d && empty) {
                            Throwable ex = error;
                            if (ex != null) {
                                errorAll(ex);
                            } else {
                                completeAll();
                            }
                            return;
                        }

                        if (empty) {
                            break;
                        }

                        for (MulticastSubscription ms : array) {
                            if (ms.get() != Long.MIN_VALUE) {
                                ms.actual.onNext(v);
                            }
                        }

                        e++;

                        if (canRequest && ++upstreamConsumed == localLimit) {
                            upstreamConsumed = 0;
                            s.get().request(localLimit);
                        }
                    }

                    if (e == r) {
                        if (isDisposed()) {
                            q.clear();
                            return;
                        }

                        boolean d = done;

                        if (d && !delayError) {
                            Throwable ex = error;
                            if (ex != null) {
                                errorAll(ex);
                                return;
                            }
                        }

                        if (d && q.isEmpty()) {
                            Throwable ex = error;
                            if (ex != null) {
                                errorAll(ex);
                            } else {
                                completeAll();
                            }
                            return;
                        }
                    }

                    for (MulticastSubscription ms : array) {
                        BackpressureHelper.produced(ms, e);
                    }
                }

                consumed = upstreamConsumed;
                missed = wip.addAndGet(-missed);
                if (missed == 0) {
                    break;
                }
                if (q == null) {
                    q = queue;
                }
            }
        }

        @SuppressWarnings("unchecked")
        void errorAll(Throwable ex) {
            for (MulticastSubscription ms : subscribers.getAndSet(TERMINATED)) {
                if (ms.get() != Long.MIN_VALUE) {
                    ms.actual.onError(ex);
                }
            }
        }

        @SuppressWarnings("unchecked")
        void completeAll() {
            for (MulticastSubscription ms : subscribers.getAndSet(TERMINATED)) {
                if (ms.get() != Long.MIN_VALUE) {
                    ms.actual.onComplete();
                }
            }
        }
    }

    static final class MulticastSubscription
    extends AtomicLong
    implements Subscription {


        private static final long serialVersionUID = 8664815189257569791L;

        final Subscriber actual;

        final MulticastProcessor parent;

        MulticastSubscription(Subscriber actual, MulticastProcessor parent) {
            this.actual = actual;
            this.parent = parent;
        }

        @Override
        public void request(long n) {
            if (SubscriptionHelper.validate(n)) {
                BackpressureHelper.addCancel(this, n);
                parent.drain();
            }
        }

        @Override
        public void cancel() {
            if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) {
                parent.remove(this);
                parent.drain(); // unblock the others
            }
        }

        public boolean isCancelled() {
            return get() == Long.MIN_VALUE;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy