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

rx.operators.OperatorParallel Maven / Gradle / Ivy

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

import rx.Observable;
import rx.Observable.Operator;
import rx.Scheduler;
import rx.Subscriber;
import rx.functions.Func1;
import rx.observables.GroupedObservable;

/**
 * Identifies unit of work that can be executed in parallel on a given Scheduler.
 */
public final class OperatorParallel implements Operator {

    private final Scheduler scheduler;
    private final Func1, Observable> f;
    private final int degreeOfParallelism;

    public OperatorParallel(Func1, Observable> f, Scheduler scheduler) {
        this.scheduler = scheduler;
        this.f = f;
        this.degreeOfParallelism = scheduler.degreeOfParallelism();
    }

    @Override
    public Subscriber call(Subscriber op) {

        Func1>, Subscriber> groupBy =
                new OperatorGroupBy(new Func1() {

                    long i = 0;

                    @Override
                    public Long call(T t) {
                        return i++ % degreeOfParallelism;
                    }

                });

        Func1>, Subscriber>> map =
                new OperatorMap, Observable>(
                        new Func1, Observable>() {

                            @Override
                            public Observable call(GroupedObservable g) {
                                // Must use observeOn not subscribeOn because we have a single source behind groupBy.
                                // The origin is already subscribed to, we are moving each group on to a new thread
                                // but the origin itself can only be on a single thread.
                                return f.call(g.observeOn(scheduler));
                            }
                        });

        // bind together Observers
        return groupBy.call(map.call(new OperatorMerge().call(op)));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy