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

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

/**
 * 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.observable.internal.operators;

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

import io.reactivex.common.*;
import io.reactivex.common.disposables.CompositeDisposable;
import io.reactivex.common.exceptions.Exceptions;
import io.reactivex.common.functions.Function;
import io.reactivex.common.internal.disposables.DisposableHelper;
import io.reactivex.common.internal.functions.ObjectHelper;
import io.reactivex.observable.Observable;
import io.reactivex.observable.ObservableSource;
import io.reactivex.observable.Observer;
import io.reactivex.observable.internal.observers.QueueDrainObserver;
import io.reactivex.observable.internal.queues.MpscLinkedQueue;
import io.reactivex.observable.internal.utils.NotificationLite;
import io.reactivex.observable.observers.*;
import io.reactivex.observable.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 s;

        final AtomicReference boundary = new AtomicReference();

        final List> ws;

        final AtomicLong windows = new AtomicLong();

        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 s) {
            if (DisposableHelper.validate(this.s, s)) {
                this.s = s;

                actual.onSubscribe(this);

                if (cancelled) {
                    return;
                }

                OperatorWindowBoundaryOpenObserver os = new OperatorWindowBoundaryOpenObserver(this);

                if (boundary.compareAndSet(null, os)) {
                    windows.getAndIncrement();
                    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) {
                RxJavaCommonPlugins.onError(t);
                return;
            }
            error = t;
            done = true;

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

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

            actual.onError(t);
        }

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

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

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

            actual.onComplete();
        }

        void error(Throwable t) {
            s.dispose();
            resources.dispose();
            onError(t);
        }

        @Override
        public void dispose() {
            cancelled = true;
        }

        @Override
        public boolean isDisposed() {
            return cancelled;
        }

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

        void drainLoop() {
            final MpscLinkedQueue q = (MpscLinkedQueue)queue;
            final Observer> a = actual;
            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 (cancelled) {
                            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);
                            cancelled = 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) {
            if (done) {
                return;
            }
            done = true;
            dispose();
            parent.close(this);
        }

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

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