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

io.reactivex.internal.operators.observable.ObservableWindowBoundarySelector Maven / Gradle / Ivy

There is a newer version: 2.2.21
Show 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.observable;

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

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.*;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.observers.QueueDrainObserver;
import io.reactivex.internal.queue.MpscLinkedQueue;
import io.reactivex.internal.util.NotificationLite;
import io.reactivex.observers.*;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.subjects.UnicastSubject;

public final class ObservableWindowBoundarySelector extends AbstractObservableWithUpstream> {
    final ObservableSource open;
    final Function> close;
    final int bufferSize;

    public ObservableWindowBoundarySelector(
            ObservableSource source,
            ObservableSource open, Function> close,
            int bufferSize) {
        super(source);
        this.open = open;
        this.close = close;
        this.bufferSize = bufferSize;
    }

    @Override
    public void subscribeActual(Observer> t) {
        source.subscribe(new WindowBoundaryMainObserver(
                new SerializedObserver>(t),
                open, close, bufferSize));
    }

    static final class WindowBoundaryMainObserver
    extends QueueDrainObserver>
    implements Disposable {
        final ObservableSource open;
        final Function> close;
        final int bufferSize;
        final CompositeDisposable resources;

        Disposable upstream;

        final AtomicReference boundary = new AtomicReference();

        final List> ws;

        final AtomicLong windows = new AtomicLong();

        final AtomicBoolean stopWindows = new AtomicBoolean();

        WindowBoundaryMainObserver(Observer> actual,
                                            ObservableSource 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(Disposable d) {
            if (DisposableHelper.validate(this.upstream, d)) {
                this.upstream = d;

                downstream.onSubscribe(this);

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

                OperatorWindowBoundaryOpenObserver os = new OperatorWindowBoundaryOpenObserver(this);

                if (boundary.compareAndSet(null, os)) {
                    open.subscribe(os);
                }
            }
        }

        @Override
        public void onNext(T t) {
            if (fastEnter()) {
                for (UnicastSubject 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.dispose();
            resources.dispose();
            onError(t);
        }

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

        @Override
        public boolean isDisposed() {
            return stopWindows.get();
        }

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

        void drainLoop() {
            final MpscLinkedQueue q = (MpscLinkedQueue)queue;
            final Observer> 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) {
                        disposeBoundary();
                        Throwable e = error;
                        if (e != null) {
                            for (UnicastSubject w : ws) {
                                w.onError(e);
                            }
                        } else {
                            for (UnicastSubject w : ws) {
                                w.onComplete();
                            }
                        }
                        ws.clear();
                        return;
                    }

                    if (empty) {
                        break;
                    }

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

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

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

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

                        w = UnicastSubject.create(bufferSize);

                        ws.add(w);
                        a.onNext(w);

                        ObservableSource p;

                        try {
                            p = ObjectHelper.requireNonNull(close.apply(wo.open), "The ObservableSource supplied is null");
                        } catch (Throwable e) {
                            Exceptions.throwIfFatal(e);
                            stopWindows.set(true);
                            a.onError(e);
                            continue;
                        }

                        OperatorWindowBoundaryCloseObserver cl = new OperatorWindowBoundaryCloseObserver(this, w);

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

                            p.subscribe(cl);
                        }

                        continue;
                    }

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

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

        @Override
        public void accept(Observer> a, Object v) {
        }

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

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

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

    static final class OperatorWindowBoundaryOpenObserver extends DisposableObserver {
        final WindowBoundaryMainObserver parent;

        OperatorWindowBoundaryOpenObserver(WindowBoundaryMainObserver 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 OperatorWindowBoundaryCloseObserver extends DisposableObserver {
        final WindowBoundaryMainObserver parent;
        final UnicastSubject w;

        boolean done;

        OperatorWindowBoundaryCloseObserver(WindowBoundaryMainObserver parent, UnicastSubject w) {
            this.parent = parent;
            this.w = w;
        }

        @Override
        public void onNext(V t) {
            dispose();
            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);
        }
    }
}