View Javadoc
1   package com.github.davidmoten.rx2.internal.flowable;
2   
3   import java.util.Iterator;
4   import java.util.List;
5   
6   import io.reactivex.Flowable;
7   import io.reactivex.functions.Function;
8   
9   public final class FlowableReverse {
10  
11      private FlowableReverse() {
12          // prevent instantiation
13      }
14  
15      @SuppressWarnings("unchecked")
16      public static <T> Flowable<T> reverse(Flowable<T> source) {
17          return source.toList().toFlowable()
18                  .flatMapIterable((Function<List<T>, Iterable<T>>) (Function<?, ?>) REVERSE_LIST);
19      }
20  
21      private static final Function<List<Object>, Iterable<Object>> REVERSE_LIST = new Function<List<Object>, Iterable<Object>>() {
22          @Override
23          public Iterable<Object> apply(List<Object> list) {
24              return reverse(list);
25          }
26      };
27  
28      private static <T> Iterable<T> reverse(final List<T> list) {
29          return new Iterable<T>() {
30  
31              @Override
32              public Iterator<T> iterator() {
33                  return new Iterator<T>() {
34  
35                      int i = list.size();
36  
37                      @Override
38                      public boolean hasNext() {
39                          return i > 0;
40                      }
41  
42                      @Override
43                      public T next() {
44                          i--;
45                          return list.get(i);
46                      }
47  
48                      @Override
49                      public void remove() {
50                          throw new UnsupportedOperationException();
51                      }
52  
53                  };
54              }
55          };
56      }
57  
58  }