RXJava - Split and Combine an Observable

时间:2015-05-12 23:11:15

标签: android system.reactive rx-java

I am new to RxJava and need some help/guidance on how to do the following:

I need to get two values from an Observable

  • a String
  • a List<.ObjectA>

I then need to apply two different filters() on this list and then finally combine all of them(String, FilteredListA, FilteredListB) into a single observable.

Is there a single chained call I can use???(need example of groupBy maybe)

Below is the sample code that is doing the same.

get '/home', to: redirect('/')

1 个答案:

答案 0 :(得分:4)

以下是groupBy的示例:

public class Multikind2 {
    static Observable<Object> getSource() {
        return Observable.just("String", Arrays.asList(1, 2, 3, 4));
    }

    enum ValueKind {
         STRING, LIST
    }

    public static void main(String[] args) {
        Func1<Object, ValueKind> kindSelector = o -> {
            if (o instanceof String) {
                return ValueKind.STRING;
            } else
            if (o instanceof List) {
                return ValueKind.LIST;
            }
            throw new IllegalArgumentException("Unsupported value: "+ o);
        };

        getSource()
        .groupBy(kindSelector)
        .flatMap(g -> {
            if (g.getKey() == ValueKind.STRING) {
                return g;
            } else
            if (g.getKey() == ValueKind.LIST) {
                Observable<Integer> flattened = g
                        .flatMapIterable(v -> (Iterable<Integer>)v)
                        .share();

                Observable<Integer> filtered1 = flattened
                        .filter(v -> v % 2 == 0);

                Observable<String> filtered2 = flattened
                        .filter(v -> v % 2 != 0)
                        .map(v -> "-> " + v);

                return filtered1.cast(Object.class)
                        .mergeWith(filtered2).cast(Object.class);
            }
            return Observable.<Object>error(
                new IllegalArgumentException("Unsupported value kind: "+ g.getKey()));
        }).subscribe(
            System.out::println, 
            Throwable::printStackTrace, 
            () -> System.out.println("Done"));
    }
}