hoc nguyen
hoc nguyen

Reputation: 73

RXAndroid: Observable wait for another observable complete

I'm using Retrofit and RxAndroid. Now i want to call api to get user information, then use this information as parameter to call another api to get more information. How should I do to achive this purpose?

P/S: It can be done with callback, but I want to do with RX-Android style

Upvotes: 1

Views: 886

Answers (3)

Cătălin Florescu
Cătălin Florescu

Reputation: 5158

If you want recursion, you should use concatMap(). This method will ensure you to have multiple calls in your specified order. flatMap() is more random.

You can check for more info on this link about this.

Upvotes: 0

Zach Bublil
Zach Bublil

Reputation: 867

You can do something like this:

Observable<User> userObservable = api.getUserInformation();
userObservable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        //do what you want this the user
                    }
                });

The following code would do the operation in a new thread,and would hit the callback on the main thread.

Upvotes: 0

damian
damian

Reputation: 2011

You can use flatMap for this.

Pseudo-code:

apiService.getUser()
    .flatMap(user -> apiService.getUserMessages(user.getId()))
    .subscribe(messages -> {

    }, error -> {

    });

Upvotes: 2

Related Questions