Buntupana
Buntupana

Reputation: 1023

Combine requests with Retrofit2 and RxJava2

I'm trying to observe two requests with the same Observer. My Observer:

private BaseObserver<LoginResponse> loginObserver = new BaseObserver<LoginResponse>(this) {
    @Override
    public void onSubscribe(Disposable d) {
        super.onSubscribe(d);
        showLoading(true);
        Log.d(TAG, "onSubscribe: ");
    }

    @Override
    public void onNext(LoginResponse response) {
        super.onNext(response);
        Log.d(TAG, "onNext: ");
    }

    @Override
    public void onComplete() {
        super.onComplete();
        showLoading(false);
        Log.d(TAG, "onComplete: ");
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        showLoading(false);
    }
};

My request is a login request build with Retrofit2:

private void sendRequest(String username, String password) {
    IResourceAPI iResourceAPI = RetrofitClient.createIResourceClient(this);
    iResourceAPI.login(new LoginRequest(username, password))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(loginObserver);
}

Now I want to launch 2 or more requests and check the responses one by one in onNext, and when the last request is checked execute onComplete with my Observer. Could anyone help me please?

Thanks in advance.

Upvotes: 0

Views: 797

Answers (2)

Geoffrey Marizy
Geoffrey Marizy

Reputation: 5531

You are looking to the merge operator:

You can combine the output of multiple Observables so that they act like a single Observable, by using the Merge operator.

Just modify your request to return an Observable:

private Observable<LoginResponse> request(String username, String password) {
    IResourceAPI iResourceAPI = RetrofitClient.createIResourceClient(this);
    iResourceAPI.login(new LoginRequest(username, password))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}

Then merge:

Observable.merge<LoginResponse>(request(...), request(...))
    .subscribeWith(loginObserver);

Upvotes: 1

Divers
Divers

Reputation: 9569

It sounds like you are looking for merge operator.

Upvotes: 1

Related Questions