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

rx.internal.operators.OnSubscribeRedo Maven / Gradle / Ivy

The newest version!
/**
 * Copyright 2014 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 rx.internal.operators;

/**
 * Copyright 2014 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.
 */

import static rx.Observable.create;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import rx.Notification;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observable.Operator;
import rx.Producer;
import rx.Scheduler;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subscriptions.SerialSubscription;

public final class OnSubscribeRedo implements OnSubscribe {

    static final Func1>, Observable> REDO_INIFINITE = new Func1>, Observable>() {
        @Override
        public Observable call(Observable> ts) {
            return ts.map(new Func1, Notification>() {
                @Override
                public Notification call(Notification terminal) {
                    return Notification.createOnNext(null);
                }
            });
        }
    };

    public static final class RedoFinite implements Func1>, Observable> {
        private final long count;

        public RedoFinite(long count) {
            this.count = count;
        }

        @Override
        public Observable call(Observable> ts) {
            return ts.map(new Func1, Notification>() {

                int num=0;
                
                @Override
                public Notification call(Notification terminalNotification) {
                    if(count == 0) {
                        return terminalNotification;
                    }
                    
                    num++;
                    if(num <= count) {
                        return Notification.createOnNext(num);
                    } else {
                        return terminalNotification;
                    }
                }
                
            }).dematerialize();
        }
    }

    public static final class RetryWithPredicate implements Func1>, Observable>> {
        private Func2 predicate;

        public RetryWithPredicate(Func2 predicate) {
            this.predicate = predicate;
        }

        @Override
        public Observable> call(Observable> ts) {
            return ts.scan(Notification.createOnNext(0), new Func2, Notification, Notification>() {
                @SuppressWarnings("unchecked")
                @Override
                public Notification call(Notification n, Notification term) {
                    final int value = n.getValue();
                    if (predicate.call(value, term.getThrowable()).booleanValue())
                        return Notification.createOnNext(value + 1);
                    else
                        return (Notification) term;
                }
            });
        }
    }

    public static  Observable retry(Observable source) {
        return retry(source, REDO_INIFINITE);
    }

    public static  Observable retry(Observable source, final long count) {
        if (count < 0)
            throw new IllegalArgumentException("count >= 0 expected");
        if (count == 0)
            return source;
        return retry(source, new RedoFinite(count));
    }

    public static  Observable retry(Observable source, Func1>, ? extends Observable> notificationHandler) {
        return create(new OnSubscribeRedo(source, notificationHandler, true, false, Schedulers.trampoline()));
    }

    public static  Observable retry(Observable source, Func1>, ? extends Observable> notificationHandler, Scheduler scheduler) {
        return create(new OnSubscribeRedo(source, notificationHandler, true, false, scheduler));
    }

    public static  Observable repeat(Observable source) {
        return repeat(source, Schedulers.trampoline());
    }

    public static  Observable repeat(Observable source, Scheduler scheduler) {
        return repeat(source, REDO_INIFINITE, scheduler);
    }

    public static  Observable repeat(Observable source, final long count) {
        return repeat(source, count, Schedulers.trampoline());
    }

    public static  Observable repeat(Observable source, final long count, Scheduler scheduler) {
        if(count == 0) {
            return Observable.empty();
        }
        if (count < 0)
            throw new IllegalArgumentException("count >= 0 expected");
        return repeat(source, new RedoFinite(count - 1), scheduler);
    }

    public static  Observable repeat(Observable source, Func1>, ? extends Observable> notificationHandler) {
        return create(new OnSubscribeRedo(source, notificationHandler, false, true, Schedulers.trampoline()));
    }

    public static  Observable repeat(Observable source, Func1>, ? extends Observable> notificationHandler, Scheduler scheduler) {
        return create(new OnSubscribeRedo(source, notificationHandler, false, true, scheduler));
    }

    public static  Observable redo(Observable source, Func1>, ? extends Observable> notificationHandler, Scheduler scheduler) {
        return create(new OnSubscribeRedo(source, notificationHandler, false, false, scheduler));
    }

    private Observable source;
    private final Func1>, ? extends Observable> controlHandlerFunction;
    private boolean stopOnComplete;
    private boolean stopOnError;
    private final Scheduler scheduler;

    private OnSubscribeRedo(Observable source, Func1>, ? extends Observable> f, boolean stopOnComplete, boolean stopOnError,
            Scheduler scheduler) {
        this.source = source;
        this.controlHandlerFunction = f;
        this.stopOnComplete = stopOnComplete;
        this.stopOnError = stopOnError;
        this.scheduler = scheduler;
    }

    @Override
    public void call(final Subscriber child) {
        final AtomicBoolean isLocked = new AtomicBoolean(true);
        final AtomicBoolean isStarted = new AtomicBoolean(false);
        // incremented when requests are made, decremented when requests are fulfilled
        final AtomicLong consumerCapacity = new AtomicLong(0l);
        final AtomicReference currentProducer = new AtomicReference();

        final Scheduler.Worker worker = scheduler.createWorker();
        child.add(worker);

        final SerialSubscription sourceSubscriptions = new SerialSubscription();
        child.add(sourceSubscriptions);

        final PublishSubject> terminals = PublishSubject.create();

        final Action0 subscribeToSource = new Action0() {
            @Override
            public void call() {
                Subscriber terminalDelegatingSubscriber = new Subscriber() {
                    @Override
                    public void onCompleted() {
                        unsubscribe();
                        terminals.onNext(Notification.createOnCompleted());
                    }

                    @Override
                    public void onError(Throwable e) {
                        unsubscribe();
                        terminals.onNext(Notification.createOnError(e));
                    }

                    @Override
                    public void onNext(T v) {
                        consumerCapacity.decrementAndGet();
                        child.onNext(v);
                    }

                    @Override
                    public void setProducer(Producer producer) {
                        currentProducer.set(producer);
                        producer.request(consumerCapacity.get());
                    }
                };
                // new subscription each time so if it unsubscribes itself it does not prevent retries
                // by unsubscribing the child subscription
                sourceSubscriptions.set(terminalDelegatingSubscriber);
                source.unsafeSubscribe(terminalDelegatingSubscriber);
            }
        };

        // the observable received by the control handler function will receive notifications of onCompleted in the case of 'repeat' 
        // type operators or notifications of onError for 'retry' this is done by lifting in a custom operator to selectively divert 
        // the retry/repeat relevant values to the control handler
        final Observable restarts = controlHandlerFunction.call(
                terminals.lift(new Operator, Notification>() {
                    @Override
                    public Subscriber> call(final Subscriber> filteredTerminals) {
                        return new Subscriber>(filteredTerminals) {
                            @Override
                            public void onCompleted() {
                                filteredTerminals.onCompleted();
                            }

                            @Override
                            public void onError(Throwable e) {
                                filteredTerminals.onError(e);
                            }

                            @Override
                            public void onNext(Notification t) {
                                if (t.isOnCompleted() && stopOnComplete)
                                    child.onCompleted();
                                else if (t.isOnError() && stopOnError)
                                    child.onError(t.getThrowable());
                                else {
                                    isLocked.set(false);
                                    filteredTerminals.onNext(t);
                                }
                            }

                            @Override
                            public void setProducer(Producer producer) {
                                producer.request(Long.MAX_VALUE);
                            }
                        };
                    }
                }));

        // subscribe to the restarts observable to know when to schedule the next redo.
        worker.schedule(new Action0() {
            @Override
            public void call() {
                restarts.unsafeSubscribe(new Subscriber(child) {
                    @Override
                    public void onCompleted() {
                        child.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        child.onError(e);
                    }

                    @Override
                    public void onNext(Object t) {
                        if (!isLocked.get() && !child.isUnsubscribed()) {
                            if (consumerCapacity.get() > 0) {
                                worker.schedule(subscribeToSource);
                            }
                        }
                    }

                    @Override
                    public void setProducer(Producer producer) {
                        producer.request(Long.MAX_VALUE);
                    }
                });
            }
        });

        child.setProducer(new Producer() {

            @Override
            public void request(long n) {
                if (isStarted.compareAndSet(false, true)) {
                    consumerCapacity.set(n);
                    worker.schedule(subscribeToSource);
                } else {
                    if (consumerCapacity.getAndAdd(n) == 0) {
                        // restart
                        worker.schedule(subscribeToSource);
                    } else {
                        if (currentProducer.get() != null) {
                            currentProducer.get().request(n);
                        }
                    }
                }
            }
        });

    }
}