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

io.reactivex.internal.operators.flowable.FlowableGroupBy Maven / Gradle / Ivy

There is a newer version: 2.2.21
Show newest version
/**
 * 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.internal.operators.flowable;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.*;

import org.reactivestreams.*;

import io.reactivex.*;
import io.reactivex.annotations.Nullable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.flowables.GroupedFlowable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.queue.SpscLinkedArrayQueue;
import io.reactivex.internal.subscriptions.*;
import io.reactivex.internal.util.BackpressureHelper;
import io.reactivex.internal.util.EmptyComponent;
import io.reactivex.plugins.RxJavaPlugins;

public final class FlowableGroupBy extends AbstractFlowableWithUpstream> {
    final Function keySelector;
    final Function valueSelector;
    final int bufferSize;
    final boolean delayError;
    final Function, ? extends Map> mapFactory;

    public FlowableGroupBy(Flowable source, Function keySelector, Function valueSelector,
            int bufferSize, boolean delayError, Function, ? extends Map> mapFactory) {
        super(source);
        this.keySelector = keySelector;
        this.valueSelector = valueSelector;
        this.bufferSize = bufferSize;
        this.delayError = delayError;
        this.mapFactory = mapFactory;
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected void subscribeActual(Subscriber> s) {

        final Map> groups;
        final Queue> evictedGroups;

        try {
            if (mapFactory == null) {
                evictedGroups = null;
                groups = new ConcurrentHashMap>();
            } else {
                evictedGroups = new ConcurrentLinkedQueue>();
                Consumer evictionAction = (Consumer) new EvictionAction(evictedGroups);
                groups = (Map) mapFactory.apply(evictionAction);
            }
        } catch (Exception e) {
            Exceptions.throwIfFatal(e);
            s.onSubscribe(EmptyComponent.INSTANCE);
            s.onError(e);
            return;
        }
        GroupBySubscriber subscriber =
                new GroupBySubscriber(s, keySelector, valueSelector, bufferSize, delayError, groups, evictedGroups);
        source.subscribe(subscriber);
    }

    public static final class GroupBySubscriber
    extends BasicIntQueueSubscription>
    implements FlowableSubscriber {

        private static final long serialVersionUID = -3688291656102519502L;

        final Subscriber> downstream;
        final Function keySelector;
        final Function valueSelector;
        final int bufferSize;
        final boolean delayError;
        final Map> groups;
        final SpscLinkedArrayQueue> queue;
        final Queue> evictedGroups;

        static final Object NULL_KEY = new Object();

        Subscription upstream;

        final AtomicBoolean cancelled = new AtomicBoolean();

        final AtomicLong requested = new AtomicLong();

        final AtomicInteger groupCount = new AtomicInteger(1);

        Throwable error;
        volatile boolean finished;
        boolean done;

        boolean outputFused;

        public GroupBySubscriber(Subscriber> actual, Function keySelector,
                Function valueSelector, int bufferSize, boolean delayError,
                Map> groups, Queue> evictedGroups) {
            this.downstream = actual;
            this.keySelector = keySelector;
            this.valueSelector = valueSelector;
            this.bufferSize = bufferSize;
            this.delayError = delayError;
            this.groups = groups;
            this.evictedGroups = evictedGroups;
            this.queue = new SpscLinkedArrayQueue>(bufferSize);
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;
                downstream.onSubscribe(this);
                s.request(bufferSize);
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }

            final SpscLinkedArrayQueue> q = this.queue;

            K key;
            try {
                key = keySelector.apply(t);
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                upstream.cancel();
                onError(ex);
                return;
            }

            boolean newGroup = false;
            Object mapKey = key != null ? key : NULL_KEY;
            GroupedUnicast group = groups.get(mapKey);
            if (group == null) {
                // if the main has been cancelled, stop creating groups
                // and skip this value
                if (cancelled.get()) {
                    return;
                }

                group = GroupedUnicast.createWith(key, bufferSize, this, delayError);
                groups.put(mapKey, group);

                groupCount.getAndIncrement();

                newGroup = true;
            }

            V v;
            try {
                v = ObjectHelper.requireNonNull(valueSelector.apply(t), "The valueSelector returned null");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                upstream.cancel();
                onError(ex);
                return;
            }

            group.onNext(v);

            completeEvictions();

            if (newGroup) {
                q.offer(group);
                drain();
            }
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            for (GroupedUnicast g : groups.values()) {
                g.onError(t);
            }
            groups.clear();
            if (evictedGroups != null) {
                evictedGroups.clear();
            }
            error = t;
            finished = true;
            drain();
        }

        @Override
        public void onComplete() {
            if (!done) {
                for (GroupedUnicast g : groups.values()) {
                    g.onComplete();
                }
                groups.clear();
                if (evictedGroups != null) {
                    evictedGroups.clear();
                }
                done = true;
                finished = true;
                drain();
            }
        }

        @Override
        public void request(long n) {
            if (SubscriptionHelper.validate(n)) {
                BackpressureHelper.add(requested, n);
                drain();
            }
        }

        @Override
        public void cancel() {
            // cancelling the main source means we don't want any more groups
            // but running groups still require new values
            if (cancelled.compareAndSet(false, true)) {
                completeEvictions();
                if (groupCount.decrementAndGet() == 0) {
                    upstream.cancel();
                }
            }
        }

        private void completeEvictions() {
            if (evictedGroups != null) {
                int count = 0;
                GroupedUnicast evictedGroup;
                while ((evictedGroup = evictedGroups.poll()) != null) {
                    evictedGroup.onComplete();
                    count++;
                }
                if (count != 0) {
                    groupCount.addAndGet(-count);
                }
            }
        }

        public void cancel(K key) {
            Object mapKey = key != null ? key : NULL_KEY;
            groups.remove(mapKey);
            if (groupCount.decrementAndGet() == 0) {
                upstream.cancel();

                if (!outputFused && getAndIncrement() == 0) {
                    queue.clear();
                }
            }
        }

        void drain() {
            if (getAndIncrement() != 0) {
                return;
            }

            if (outputFused) {
                drainFused();
            } else {
                drainNormal();
            }
        }

        void drainFused() {
            int missed = 1;

            final SpscLinkedArrayQueue> q = this.queue;
            final Subscriber> a = this.downstream;

            for (;;) {
                if (cancelled.get()) {
                    return;
                }

                boolean d = finished;

                if (d && !delayError) {
                    Throwable ex = error;
                    if (ex != null) {
                        q.clear();
                        a.onError(ex);
                        return;
                    }
                }

                a.onNext(null);

                if (d) {
                    Throwable ex = error;
                    if (ex != null) {
                        a.onError(ex);
                    } else {
                        a.onComplete();
                    }
                    return;
                }

                missed = addAndGet(-missed);
                if (missed == 0) {
                    return;
                }
            }
        }

        void drainNormal() {
            int missed = 1;

            final SpscLinkedArrayQueue> q = this.queue;
            final Subscriber> a = this.downstream;

            for (;;) {

                long r = requested.get();
                long e = 0L;

                while (e != r) {
                    boolean d = finished;

                    GroupedFlowable t = q.poll();

                    boolean empty = t == null;

                    if (checkTerminated(d, empty, a, q)) {
                        return;
                    }

                    if (empty) {
                        break;
                    }

                    a.onNext(t);

                    e++;
                }

                if (e == r && checkTerminated(finished, q.isEmpty(), a, q)) {
                    return;
                }

                if (e != 0L) {
                    if (r != Long.MAX_VALUE) {
                        requested.addAndGet(-e);
                    }
                    upstream.request(e);
                }

                missed = addAndGet(-missed);
                if (missed == 0) {
                    break;
                }
            }
        }

        boolean checkTerminated(boolean d, boolean empty, Subscriber a, SpscLinkedArrayQueue q) {
            if (cancelled.get()) {
                q.clear();
                return true;
            }

            if (delayError) {
                if (d && empty) {
                    Throwable ex = error;
                    if (ex != null) {
                        a.onError(ex);
                    } else {
                        a.onComplete();
                    }
                    return true;
                }
            } else {
                if (d) {
                    Throwable ex = error;
                    if (ex != null) {
                        q.clear();
                        a.onError(ex);
                        return true;
                    } else if (empty) {
                        a.onComplete();
                        return true;
                    }
                }
            }

            return false;
        }

        @Override
        public int requestFusion(int mode) {
            if ((mode & ASYNC) != 0) {
                outputFused = true;
                return ASYNC;
            }
            return NONE;
        }

        @Nullable
        @Override
        public GroupedFlowable poll() {
            return queue.poll();
        }

        @Override
        public void clear() {
            queue.clear();
        }

        @Override
        public boolean isEmpty() {
            return queue.isEmpty();
        }
    }

    static final class EvictionAction implements Consumer> {

        final Queue> evictedGroups;

        EvictionAction(Queue> evictedGroups) {
            this.evictedGroups = evictedGroups;
        }

        @Override
        public void accept(GroupedUnicast value) {
            evictedGroups.offer(value);
        }
    }

    static final class GroupedUnicast extends GroupedFlowable {

        final State state;

        public static  GroupedUnicast createWith(K key, int bufferSize, GroupBySubscriber parent, boolean delayError) {
            State state = new State(bufferSize, parent, key, delayError);
            return new GroupedUnicast(key, state);
        }

        protected GroupedUnicast(K key, State state) {
            super(key);
            this.state = state;
        }

        @Override
        protected void subscribeActual(Subscriber s) {
            state.subscribe(s);
        }

        public void onNext(T t) {
            state.onNext(t);
        }

        public void onError(Throwable e) {
            state.onError(e);
        }

        public void onComplete() {
            state.onComplete();
        }
    }

    static final class State extends BasicIntQueueSubscription implements Publisher {

        private static final long serialVersionUID = -3852313036005250360L;

        final K key;
        final SpscLinkedArrayQueue queue;
        final GroupBySubscriber parent;
        final boolean delayError;

        final AtomicLong requested = new AtomicLong();

        volatile boolean done;
        Throwable error;

        final AtomicBoolean cancelled = new AtomicBoolean();

        final AtomicReference> actual = new AtomicReference>();

        final AtomicBoolean once = new AtomicBoolean();

        boolean outputFused;

        int produced;

        State(int bufferSize, GroupBySubscriber parent, K key, boolean delayError) {
            this.queue = new SpscLinkedArrayQueue(bufferSize);
            this.parent = parent;
            this.key = key;
            this.delayError = delayError;
        }

        @Override
        public void request(long n) {
            if (SubscriptionHelper.validate(n)) {
                BackpressureHelper.add(requested, n);
                drain();
            }
        }

        @Override
        public void cancel() {
            if (cancelled.compareAndSet(false, true)) {
                parent.cancel(key);
                drain();
            }
        }

        @Override
        public void subscribe(Subscriber s) {
            if (once.compareAndSet(false, true)) {
                s.onSubscribe(this);
                actual.lazySet(s);
                drain();
            } else {
                EmptySubscription.error(new IllegalStateException("Only one Subscriber allowed!"), s);
            }
        }

        public void onNext(T t) {
            queue.offer(t);
            drain();
        }

        public void onError(Throwable e) {
            error = e;
            done = true;
            drain();
        }

        public void onComplete() {
            done = true;
            drain();
        }

        void drain() {
            if (getAndIncrement() != 0) {
                return;
            }
            if (outputFused) {
                drainFused();
            } else {
                drainNormal();
            }
        }

        void drainFused() {
            int missed = 1;

            final SpscLinkedArrayQueue q = this.queue;
            Subscriber a = this.actual.get();

            for (;;) {
                if (a != null) {
                    if (cancelled.get()) {
                        return;
                    }

                    boolean d = done;

                    if (d && !delayError) {
                        Throwable ex = error;
                        if (ex != null) {
                            q.clear();
                            a.onError(ex);
                            return;
                        }
                    }

                    a.onNext(null);

                    if (d) {
                        Throwable ex = error;
                        if (ex != null) {
                            a.onError(ex);
                        } else {
                            a.onComplete();
                        }
                        return;
                    }
                }

                missed = addAndGet(-missed);
                if (missed == 0) {
                    return;
                }

                if (a == null) {
                    a = this.actual.get();
                }
            }
        }

        void drainNormal() {
            int missed = 1;

            final SpscLinkedArrayQueue q = queue;
            final boolean delayError = this.delayError;
            Subscriber a = actual.get();
            for (;;) {
                if (a != null) {
                    long r = requested.get();
                    long e = 0;

                    while (e != r) {
                        boolean d = done;
                        T v = q.poll();
                        boolean empty = v == null;

                        if (checkTerminated(d, empty, a, delayError, e)) {
                            return;
                        }

                        if (empty) {
                            break;
                        }

                        a.onNext(v);

                        e++;
                    }

                    if (e == r && checkTerminated(done, q.isEmpty(), a, delayError, e)) {
                        return;
                    }

                    if (e != 0L) {
                        if (r != Long.MAX_VALUE) {
                            requested.addAndGet(-e);
                        }
                        parent.upstream.request(e);
                    }
                }

                missed = addAndGet(-missed);
                if (missed == 0) {
                    break;
                }
                if (a == null) {
                    a = actual.get();
                }
            }
        }

        boolean checkTerminated(boolean d, boolean empty, Subscriber a, boolean delayError, long emitted) {
            if (cancelled.get()) {
                // make sure buffered items can get replenished
                while (queue.poll() != null) {
                    emitted++;
                }
                if (emitted != 0) {
                    parent.upstream.request(emitted);
                }
                return true;
            }

            if (d) {
                if (delayError) {
                    if (empty) {
                        Throwable e = error;
                        if (e != null) {
                            a.onError(e);
                        } else {
                            a.onComplete();
                        }
                        return true;
                    }
                } else {
                    Throwable e = error;
                    if (e != null) {
                        queue.clear();
                        a.onError(e);
                        return true;
                    } else
                    if (empty) {
                        a.onComplete();
                        return true;
                    }
                }
            }

            return false;
        }

        @Override
        public int requestFusion(int mode) {
            if ((mode & ASYNC) != 0) {
                outputFused = true;
                return ASYNC;
            }
            return NONE;
        }

        @Nullable
        @Override
        public T poll() {
            T v = queue.poll();
            if (v != null) {
                produced++;
                return v;
            }
            tryReplenish();
            return null;
        }

        @Override
        public boolean isEmpty() {
            if (queue.isEmpty()) {
                tryReplenish();
                return true;
            }
            return false;
        }

        void tryReplenish() {
            int p = produced;
            if (p != 0) {
                produced = 0;
                parent.upstream.request(p);
            }
        }

        @Override
        public void clear() {
            // make sure buffered items can get replenished
            SpscLinkedArrayQueue q = queue;
            while (q.poll() != null) {
                produced++;
            }
            tryReplenish();
        }
    }
}