package com.github.davidmoten.rx2.internal.flowable;

import java.util.Iterator;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;

public final class FlowableReverse {

    private FlowableReverse() {
        // prevent instantiation
    }

    @SuppressWarnings("unchecked")
    public static <T> Flowable<T> reverse(Flowable<T> source) {
        return source.toList().toFlowable()
                .flatMap((Function<List<T>, Flowable<T>>) (Function<?, ?>) REVERSE_LIST);
    }

    private static final Function<List<Object>, Flowable<Object>> REVERSE_LIST = new Function<List<Object>, Flowable<Object>>() {
        @Override
        public Flowable<Object> apply(List<Object> list) {
            return Flowable.fromIterable(reverse(list));
        }
    };

    private static <T> Iterable<T> reverse(final List<T> list) {
        return new Iterable<T>() {

            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {

                    int i = list.size();

                    @Override
                    public boolean hasNext() {
                        return i > 0;
                    }

                    @Override
                    public T next() {
                        i--;
                        return list.get(i);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }

                };
            }
        };
    }

}

@@ -446,16 +446,24 @@
 .flatMap
+Iterable
 ((Functi
@@ -474,20 +474,20 @@
 ist%3CT%3E, 
-Flow
+Iter
 able%3CT%3E%3E
@@ -567,36 +567,36 @@
 n%3CList%3CObject%3E, 
-Flow
+Iter
 able%3CObject%3E%3E RE
@@ -635,20 +635,20 @@
 bject%3E, 
-Flow
+Iter
 able%3CObj
@@ -690,20 +690,20 @@
  public 
-Flow
+Iter
 able%3CObj
@@ -757,30 +757,8 @@
 urn 
-Flowable.fromIterable(
 reve
@@ -766,17 +766,16 @@
 se(list)
-)
 ;%0A      

simplify reverse using flatMapIterable as suggested by @akarnokd