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

io.reactivex.internal.operators.flowable.FlowableWindowBoundarySelector 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.internal.operators.flowable;

import java.util.*;
import java.util.concurrent.atomic.*;

import org.reactivestreams.*;

import io.reactivex.Flowable;
import io.reactivex.disposables.*;
import io.reactivex.exceptions.MissingBackpressureException;
import io.reactivex.functions.Function;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.fuseable.SimplePlainQueue;
import io.reactivex.internal.queue.MpscLinkedQueue;
import io.reactivex.internal.subscribers.QueueDrainSubscriber;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.internal.util.NotificationLite;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.processors.UnicastProcessor;
import io.reactivex.subscribers.*;

public final class FlowableWindowBoundarySelector extends AbstractFlowableWithUpstream> {
    final Publisher open;
    final Function> close;
    final int bufferSize;

    public FlowableWindowBoundarySelector(
            Flowable source,
            Publisher open, Function> close,
            int bufferSize) {
        super(source);
        this.open = open;
        this.close = close;
        this.bufferSize = bufferSize;
    }

    @Override
    protected void subscribeActual(Subscriber> s) {
        source.subscribe(new WindowBoundaryMainSubscriber(
                new SerializedSubscriber>(s),
                open, close, bufferSize));
    }

    static final class WindowBoundaryMainSubscriber
    extends QueueDrainSubscriber>
    implements Subscription {
        final Publisher open;
        final Function> close;
        final int bufferSize;
        final CompositeDisposable resources;

        Subscription upstream;

        final AtomicReference boundary = new AtomicReference();

        final List> ws;

        final AtomicLong windows = new AtomicLong();

        final AtomicBoolean stopWindows = new AtomicBoolean();

        WindowBoundaryMainSubscriber(Subscriber> actual,
                Publisher open, Function> close, int bufferSize) {
            super(actual, new MpscLinkedQueue());
            this.open = open;
            this.close = close;
            this.bufferSize = bufferSize;
            this.resources = new CompositeDisposable();
            this.ws = new ArrayList>();
            windows.lazySet(1);
        }

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

                downstream.onSubscribe(this);

                if (stopWindows.get()) {
                    return;
                }

                OperatorWindowBoundaryOpenSubscriber os = new OperatorWindowBoundaryOpenSubscriber(this);

                if (boundary.compareAndSet(null, os)) {
                    s.request(Long.MAX_VALUE);
                    open.subscribe(os);
                }
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            if (fastEnter()) {
                for (UnicastProcessor w : ws) {
                    w.onNext(t);
                }
                if (leave(-1) == 0) {
                    return;
                }
            } else {
                queue.offer(NotificationLite.next(t));
                if (!enter()) {
                    return;
                }
            }
            drainLoop();
        }

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

            if (enter()) {
                drainLoop();
            }

            if (windows.decrementAndGet() == 0) {
                resources.dispose();
            }

            downstream.onError(t);
        }

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

            if (enter()) {
                drainLoop();
            }

            if (windows.decrementAndGet() == 0) {
                resources.dispose();
            }

            downstream.onComplete();
        }

        void error(Throwable t) {
            upstream.cancel();
            resources.dispose();
            DisposableHelper.dispose(boundary);

            downstream.onError(t);
        }

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

        @Override
        public void cancel() {
            if (stopWindows.compareAndSet(false, true)) {
                DisposableHelper.dispose(boundary);
                if (windows.decrementAndGet() == 0) {
                    upstream.cancel();
                }
            }
        }

        void dispose() {
            resources.dispose();
            DisposableHelper.dispose(boundary);
        }

        void drainLoop() {
            final SimplePlainQueue q = queue;
            final Subscriber> a = downstream;
            final List> ws = this.ws;
            int missed = 1;

            for (;;) {

                for (;;) {
                    boolean d = done;
                    Object o = q.poll();

                    boolean empty = o == null;

                    if (d && empty) {
                        dispose();
                        Throwable e = error;
                        if (e != null) {
                            for (UnicastProcessor w : ws) {
                                w.onError(e);
                            }
                        } else {
                            for (UnicastProcessor w : ws) {
                                w.onComplete();
                            }
                        }
                        ws.clear();
                        return;
                    }

                    if (empty) {
                        break;
                    }

                    if (o instanceof WindowOperation) {
                        @SuppressWarnings("unchecked")
                        WindowOperation wo = (WindowOperation) o;

                        UnicastProcessor w = wo.w;
                        if (w != null) {
                            if (ws.remove(wo.w)) {
                                wo.w.onComplete();

                                if (windows.decrementAndGet() == 0) {
                                    dispose();
                                    return;
                                }
                            }
                            continue;
                        }

                        if (stopWindows.get()) {
                            continue;
                        }

                        w = UnicastProcessor.create(bufferSize);

                        long r = requested();
                        if (r != 0L) {
                            ws.add(w);
                            a.onNext(w);
                            if (r != Long.MAX_VALUE) {
                                produced(1);
                            }
                        } else {
                            cancel();
                            a.onError(new MissingBackpressureException("Could not deliver new window due to lack of requests"));
                            continue;
                        }

                        Publisher p;

                        try {
                            p = ObjectHelper.requireNonNull(close.apply(wo.open), "The publisher supplied is null");
                        } catch (Throwable e) {
                            cancel();
                            a.onError(e);
                            continue;
                        }

                        OperatorWindowBoundaryCloseSubscriber cl = new OperatorWindowBoundaryCloseSubscriber(this, w);

                        if (resources.add(cl)) {
                            windows.getAndIncrement();

                            p.subscribe(cl);
                        }

                        continue;
                    }

                    for (UnicastProcessor w : ws) {
                        w.onNext(NotificationLite.getValue(o));
                    }
                }

                missed = leave(-missed);
                if (missed == 0) {
                    break;
                }
            }
        }

        @Override
        public boolean accept(Subscriber> a, Object v) {
            // not used by this operator
            return false;
        }

        void open(B b) {
            queue.offer(new WindowOperation(null, b));
            if (enter()) {
                drainLoop();
            }
        }

        void close(OperatorWindowBoundaryCloseSubscriber w) {
            resources.delete(w);
            queue.offer(new WindowOperation(w.w, null));
            if (enter()) {
                drainLoop();
            }
        }
    }

    static final class WindowOperation {
        final UnicastProcessor w;
        final B open;
        WindowOperation(UnicastProcessor w, B open) {
            this.w = w;
            this.open = open;
        }
    }

    static final class OperatorWindowBoundaryOpenSubscriber extends DisposableSubscriber {
        final WindowBoundaryMainSubscriber parent;

        OperatorWindowBoundaryOpenSubscriber(WindowBoundaryMainSubscriber parent) {
            this.parent = parent;
        }

        @Override
        public void onNext(B t) {
            parent.open(t);
        }

        @Override
        public void onError(Throwable t) {
            parent.error(t);
        }

        @Override
        public void onComplete() {
            parent.onComplete();
        }
    }

    static final class OperatorWindowBoundaryCloseSubscriber extends DisposableSubscriber {
        final WindowBoundaryMainSubscriber parent;
        final UnicastProcessor w;

        boolean done;

        OperatorWindowBoundaryCloseSubscriber(WindowBoundaryMainSubscriber parent, UnicastProcessor w) {
            this.parent = parent;
            this.w = w;
        }

        @Override
        public void onNext(V t) {
            cancel();
            onComplete();
        }

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

        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            parent.close(this);
        }
    }
}