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

hu.akarnokd.rxjava2.internal.operators.OperatorBufferBoundary Maven / Gradle / Ivy

There is a newer version: 2.0.0-RC3
Show newest version
/**
 * Copyright 2015 David Karnok and Netflix, Inc.
 * 
 * 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 hu.akarnokd.rxjava2.internal.operators;

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

import org.reactivestreams.*;

import hu.akarnokd.rxjava2.Observable.Operator;
import hu.akarnokd.rxjava2.disposables.*;
import hu.akarnokd.rxjava2.functions.*;
import hu.akarnokd.rxjava2.internal.disposables.SetCompositeResource;
import hu.akarnokd.rxjava2.internal.queue.MpscLinkedQueue;
import hu.akarnokd.rxjava2.internal.subscribers.*;
import hu.akarnokd.rxjava2.internal.subscriptions.SubscriptionHelper;
import hu.akarnokd.rxjava2.internal.util.QueueDrainHelper;
import hu.akarnokd.rxjava2.plugins.RxJavaPlugins;
import hu.akarnokd.rxjava2.subscribers.SerializedSubscriber;

public final class OperatorBufferBoundary, Open, Close> implements Operator {
    final Supplier bufferSupplier;
    final Publisher bufferOpen;
    final Function> bufferClose;

    public OperatorBufferBoundary(Publisher bufferOpen,
            Function> bufferClose, Supplier bufferSupplier) {
        this.bufferOpen = bufferOpen;
        this.bufferClose = bufferClose;
        this.bufferSupplier = bufferSupplier;
    }
    
    @Override
    public Subscriber apply(Subscriber t) {
        return new BufferBoundarySubscriber(
                new SerializedSubscriber(t),
                bufferOpen, bufferClose, bufferSupplier
                );
    }
    
    static final class BufferBoundarySubscriber, Open, Close>
    extends QueueDrainSubscriber implements Subscription, Disposable {
        final Publisher bufferOpen;
        final Function> bufferClose;
        final Supplier bufferSupplier;
        final SetCompositeResource resources;
        
        Subscription s;
        
        final List buffers;
        
        volatile int windows;
        @SuppressWarnings("rawtypes")
        static final AtomicIntegerFieldUpdater WINDOWS =
                AtomicIntegerFieldUpdater.newUpdater(BufferBoundarySubscriber.class, "windows");

        public BufferBoundarySubscriber(Subscriber actual, 
                Publisher bufferOpen,
                Function> bufferClose,
                Supplier bufferSupplier) {
            super(actual, new MpscLinkedQueue());
            this.bufferOpen = bufferOpen;
            this.bufferClose = bufferClose;
            this.bufferSupplier = bufferSupplier;
            this.buffers = new LinkedList();
            this.resources = new SetCompositeResource(Disposables.consumeAndDispose());
        }
        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validateSubscription(this.s, s)) {
                return;
            }
            this.s = s;
            
            BufferOpenSubscriber bos = new BufferOpenSubscriber(this);
            resources.add(bos);

            actual.onSubscribe(this);
            
            WINDOWS.lazySet(this, 1);
            bufferOpen.subscribe(bos);
            
            s.request(Long.MAX_VALUE);
        }
        
        @Override
        public void onNext(T t) {
            synchronized (t) {
                for (U b : buffers) {
                    b.add(t);
                }
            }
        }
        
        @Override
        public void onError(Throwable t) {
            cancel();
            cancelled = true;
            synchronized (this) {
                buffers.clear();
            }
            actual.onError(t);
        }
        
        @Override
        public void onComplete() {
            if (WINDOWS.decrementAndGet(this) == 0) {
                complete();
            }
        }
        
        void complete() {
            List list;
            synchronized (this) {
                list = new ArrayList(buffers);
                buffers.clear();
            }
            
            Queue q = queue;
            for (U u : list) {
                q.offer(u);
            }
            done = true;
            if (enter()) {
                QueueDrainHelper.drainMaxLoop(q, actual, false, this, this);
            }
        }
        
        @Override
        public void request(long n) {
            requested(n);
        }
        
        @Override
        public void dispose() {
            resources.dispose();
        }
        
        @Override
        public void cancel() {
            if (!cancelled) {
                cancelled = true;
                dispose();
            }
        }
        
        @Override
        public boolean accept(Subscriber a, U v) {
            a.onNext(v);
            return true;
        }
        
        void open(Open window) {
            if (cancelled) {
                return;
            }
            
            U b;
            
            try {
                b = bufferSupplier.get();
            } catch (Throwable e) {
                onError(e);
                return;
            }
            
            if (b == null) {
                onError(new NullPointerException("The buffer supplied is null"));
                return;
            }

            Publisher p;
            
            try {
                p = bufferClose.apply(window);
            } catch (Throwable e) {
                onError(e);
                return;
            }
            
            if (p == null) {
                onError(new NullPointerException("The buffer closing publisher is null"));
                return;
            }
            
            if (cancelled) {
                return;
            }

            synchronized (this) {
                if (cancelled) {
                    return;
                }
                buffers.add(b);
            }
            
            BufferCloseSubscriber bcs = new BufferCloseSubscriber(b, this);
            resources.add(bcs);
            
            WINDOWS.getAndIncrement(this);
            
            p.subscribe(bcs);
        }
        
        void openFinished(Disposable d) {
            if (resources.remove(d)) {
                if (WINDOWS.decrementAndGet(this) == 0) {
                    complete();
                }
            }
        }
        
        void close(U b, Disposable d) {
            
            boolean e;
            synchronized (this) {
                e = buffers.remove(b);
            }
            
            if (e) {
                fastpathOrderedEmitMax(b, false, this);
            }
            
            if (resources.remove(d)) {
                if (WINDOWS.decrementAndGet(this) == 0) {
                    complete();
                }
            }
        }
    }
    
    static final class BufferOpenSubscriber, Open, Close>
    extends DisposableSubscriber {
        final BufferBoundarySubscriber parent;
        
        boolean done;
        
        public BufferOpenSubscriber(BufferBoundarySubscriber parent) {
            this.parent = parent;
        }
        @Override
        public void onNext(Open t) {
            if (done) {
                return;
            }
            parent.open(t);
        }
        
        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            parent.onError(t);
        }
        
        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            parent.openFinished(this);
        }
    }
    
    static final class BufferCloseSubscriber, Open, Close>
    extends DisposableSubscriber {
        final BufferBoundarySubscriber parent;
        final U value;
        boolean done;
        public BufferCloseSubscriber(U value, BufferBoundarySubscriber parent) {
            this.parent = parent;
            this.value = value;
        }
        
        @Override
        public void onNext(Close t) {
            onComplete();
        }
        
        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            parent.onError(t);
        }
        
        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            parent.close(value, this);
        }
    }
}