Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava/Android: Combine result of two dependent Observables

I have two Observables.

  1. Observable<A> getAObservable() Returns Observable of A
  2. Observable<B> getBObservable(A) Returns Observable of 'B'.

Here Observable<A> should execute before Observable<B> so that it can pass its result A to getBObservable() method. Now once Observable<B> completes I need to combine the result of these observable and Observable<AB> should returns.

Options Tried:

  1. Take Observable<A> and apply flatMap on it so that it transform result in B. Now at this point I am not having access to A data. Hence I can't return Observable

    1. I can use zip so that once I get the result of both Observable<A> and Observable<B>, I can combine their result to AB. But here I cannot set dependency that Observable<A> should execute before Observable<B> and I can't pass the result of Observable<A> to Observable<B>

Codebase:

public class Data {

    A a = new A();
    public Observable<AB> getABContext() {
        A a = new A();

        return getAObservable()
                .flatMap(new Func1<A, Observable<AB>>() {
                    @Override
                    public Observable<AB> call(final A a) {
                        return getBObservable(a)
                                .flatMap(new Func1<B, Observable<AB>>() {
                                    @Override
                                    public Observable<AB> call(B b) {
                                        return Observable.just(new AB(a, b));
                                    }
                                });
                    }
                });
    }

    private Observable<A> getAObservable() {
        return Observable.just(a);
    }

    private Observable<B> getBObservable(A a) {
        return Observable.just(new B(a));
    }

    private static class A {

    }

    private static class B {
        B (A a) {

        }
    }

    private static class AB {
        AB (A a, B b) {

        }
    }

}
like image 861
Sagar Trehan Avatar asked Apr 15 '16 06:04

Sagar Trehan


1 Answers

See flatMap documentation. It has overloaded method, that apply zip function:

    Observable<Pair<A, B>> abObservable = getAObservable()
      .flatMap(
        new Func1<A, Observable<? extends B>>() {
            @Override
            public Observable<? extends B> call(A a) {
                return getBObservable(a);
            }
        },
        new Func2<A, B, Pair<A, B>>() {
            @Override
            public Pair<A, B> call(A a1, B b1) {
                return new Pair<>(a1, b1);
            }
        }
      );
like image 76
zella Avatar answered Sep 27 '22 18:09

zella