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

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

/**
 * 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.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import org.reactivestreams.*;

import hu.akarnokd.rxjava2.Observable.Operator;
import hu.akarnokd.rxjava2.disposables.Disposable;
import hu.akarnokd.rxjava2.functions.*;
import hu.akarnokd.rxjava2.internal.subscribers.*;
import hu.akarnokd.rxjava2.internal.subscriptions.*;
import hu.akarnokd.rxjava2.plugins.RxJavaPlugins;
import hu.akarnokd.rxjava2.subscribers.SerializedSubscriber;

public final class OperatorTimeout implements Operator {
    final Supplier> firstTimeoutSelector; 
    final Function> timeoutSelector; 
    final Publisher other;

    public OperatorTimeout(Supplier> firstTimeoutSelector,
            Function> timeoutSelector, Publisher other) {
        this.firstTimeoutSelector = firstTimeoutSelector;
        this.timeoutSelector = timeoutSelector;
        this.other = other;
    }

    @Override
    public Subscriber apply(Subscriber t) {
        if (other == null) {
            return new TimeoutSubscriber(
                    new SerializedSubscriber(t), 
                    firstTimeoutSelector, timeoutSelector);
        }
        return new TimeoutOtherSubscriber(t, firstTimeoutSelector, timeoutSelector, other);
    }
    
    static final class TimeoutSubscriber implements Subscriber, Subscription, OnTimeout {
        final Subscriber actual;
        final Supplier> firstTimeoutSelector; 
        final Function> timeoutSelector; 

        Subscription s;
        
        volatile boolean cancelled;
        
        volatile long index;
        
        volatile Disposable timeout;
        @SuppressWarnings("rawtypes")
        static final AtomicReferenceFieldUpdater TIMEOUT =
                AtomicReferenceFieldUpdater.newUpdater(TimeoutSubscriber.class, Disposable.class, "timeout");
        
        static final Disposable CANCELLED = new Disposable() {
            @Override
            public void dispose() { }
        };

        public TimeoutSubscriber(Subscriber actual, 
                Supplier> firstTimeoutSelector,
                Function> timeoutSelector) {
            this.actual = actual;
            this.firstTimeoutSelector = firstTimeoutSelector;
            this.timeoutSelector = timeoutSelector;
        }
        
        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validateSubscription(this.s, s)) {
                return;
            }
            this.s = s;
            
            if (cancelled) {
                return;
            }
            
            Subscriber a = actual;
            
            Publisher p;
            
            if (firstTimeoutSelector != null) {
                try {
                    p = firstTimeoutSelector.get();
                } catch (Exception ex) {
                    cancel();
                    EmptySubscription.error(ex, a);
                    return;
                }
                
                if (p == null) {
                    cancel();
                    EmptySubscription.error(new NullPointerException("The first timeout publisher is null"), a);
                    return;
                }
                
                TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, 0);
                
                if (TIMEOUT.compareAndSet(this, null, tis)) {
                    a.onSubscribe(s);
                    p.subscribe(tis);
                }
            } else {
                a.onSubscribe(s);
            }
        }
        
        @Override
        public void onNext(T t) {
            long idx = index + 1;
            index = idx;

            actual.onNext(t);
            
            Disposable d = timeout;
            if (d != null) {
                d.dispose();
            }
            
            Publisher p;
            
            try {
                p = timeoutSelector.apply(t);
            } catch (Throwable e) {
                cancel();
                actual.onError(e);
                return;
            }
            
            if (p == null) {
                cancel();
                actual.onError(new NullPointerException("The publisher returned is null"));
                return;
            }
            
            TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, idx);
            
            if (TIMEOUT.compareAndSet(this, d, tis)) {
                p.subscribe(tis);
            }
        }
        
        @Override
        public void onError(Throwable t) {
            cancel();
            actual.onError(t);
        }
        
        @Override
        public void onComplete() {
            cancel();
            actual.onComplete();
        }
        
        @Override
        public void request(long n) {
            s.request(n);
        }
        
        @Override
        public void cancel() {
            cancelled = true;
            s.cancel();
            
            Disposable d = timeout;
            if (d != CANCELLED) {
                d = TIMEOUT.getAndSet(this, CANCELLED);
                if (d != CANCELLED && d != null) {
                    d.dispose();
                }
            }
        }
        
        @Override
        public void timeout(long idx) {
            if (idx == index) {
                cancel();
                actual.onError(new TimeoutException());
            }
        }
    }
    
    interface OnTimeout {
        void timeout(long index);
        
        void onError(Throwable e);
    }
    
    static final class TimeoutInnerSubscriber extends DisposableSubscriber {
        final OnTimeout parent;
        final long index;
        
        boolean done;
        
        public TimeoutInnerSubscriber(OnTimeout parent, final long index) {
            this.parent = parent;
            this.index = index;
        }
        
        @Override
        public void onNext(Object t) {
            if (done) {
                return;
            }
            done = true;
            cancel();
            parent.timeout(index);
        }
        
        @Override
        public void onError(Throwable t) {
            parent.onError(t);
        }
        
        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            parent.timeout(index);
        }
    }
    
    static final class TimeoutOtherSubscriber implements Subscriber, Disposable, OnTimeout {
        final Subscriber actual;
        final Supplier> firstTimeoutSelector; 
        final Function> timeoutSelector;
        final Publisher other;
        final FullArbiter arbiter;
        
        Subscription s;
        
        boolean done;
        
        volatile boolean cancelled;
        
        volatile long index;
        
        volatile Disposable timeout;
        @SuppressWarnings("rawtypes")
        static final AtomicReferenceFieldUpdater TIMEOUT =
                AtomicReferenceFieldUpdater.newUpdater(TimeoutOtherSubscriber.class, Disposable.class, "timeout");
        
        static final Disposable CANCELLED = new Disposable() {
            @Override
            public void dispose() { }
        };

        public TimeoutOtherSubscriber(Subscriber actual,
                Supplier> firstTimeoutSelector,
                Function> timeoutSelector, Publisher other) {
            this.actual = actual;
            this.firstTimeoutSelector = firstTimeoutSelector;
            this.timeoutSelector = timeoutSelector;
            this.other = other;
            this.arbiter = new FullArbiter(actual, this, 8);
        }
        
        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validateSubscription(this.s, s)) {
                return;
            }
            this.s = s;
            
            if (!arbiter.setSubscription(s)) {
                return;
            }
            Subscriber a = actual;
            
            if (firstTimeoutSelector != null) {
                Publisher p;
                
                try {
                    p = firstTimeoutSelector.get();
                } catch (Exception ex) {
                    dispose();
                    EmptySubscription.error(ex, a);
                    return;
                }
                
                if (p == null) {
                    dispose();
                    EmptySubscription.error(new NullPointerException("The first timeout publisher is null"), a);
                    return;
                }
                
                TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, 0);
                
                if (TIMEOUT.compareAndSet(this, null, tis)) {
                    a.onSubscribe(arbiter);
                    p.subscribe(tis);
                }
            } else {
                a.onSubscribe(arbiter);
            }
        }
        
        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            long idx = index + 1;
            index = idx;

            if (!arbiter.onNext(t, s)) {
                return;
            }
            
            Disposable d = timeout;
            if (d != null) {
                d.dispose();
            }
            
            Publisher p;
            
            try {
                p = timeoutSelector.apply(t);
            } catch (Throwable e) {
                actual.onError(e);
                return;
            }
            
            if (p == null) {
                actual.onError(new NullPointerException("The publisher returned is null"));
                return;
            }
            
            TimeoutInnerSubscriber tis = new TimeoutInnerSubscriber(this, idx);
            
            if (TIMEOUT.compareAndSet(this, d, tis)) {
                p.subscribe(tis);
            }
        }
        
        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            dispose();
            arbiter.onError(t, s);
        }
        
        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            dispose();
            arbiter.onComplete(s);
        }
        
        @Override
        public void dispose() {
            cancelled = true;
            s.cancel();
            
            Disposable d = timeout;
            if (d != CANCELLED) {
                d = TIMEOUT.getAndSet(this, CANCELLED);
                if (d != CANCELLED && d != null) {
                    d.dispose();
                }
            }
        }
        
        @Override
        public void timeout(long idx) {
            if (idx == index) {
                dispose();
                other.subscribe(new FullArbiterSubscriber(arbiter));
            }
        }
    }
}