Brandon Slaght
Brandon Slaght

Reputation: 1067

Handling multiple requests returning the same type in Retrofit

I have a fragment set up like so:

public mFragment extends Fragment implements Callback<mType> {

    ...

@Override
public void onViewCreated(View v, Bundle sis) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("MYURL").addConverterFactory(GsonConverterFactory.create()).build();
    api mAPI = retrofit.create(api.class);
    Call<mType> call1 = mAPI.query1("query1"));
    Call<mType> call2 = mAPI.query2("query2"));
    call1.enqueue(this);
    call2.enqueue(this);
}

@Override
public void onFailure(Throwable t) {
    ...
}

@Override
public void onResponse(final Response<mType> response, Retrofit retrofit) {
    ...
}
}

I need to make 2 api calls, which both return the same type. However, I want to handle both of them in different onResponse methods as I need to do distinct things to both of them. This is under Retrofit 2.0. This is an API of a different service, so I do not have access to change any of the responses.

Is there a way to specify which method a Retrofit Call calls back to? I'm really hoping that this has as clean of a solution as if I were using two different return types. If worst comes to worst I can just duplicate the object and rename it but I think there is a "correct" way to do this.

Upvotes: 0

Views: 1592

Answers (1)

Ankit Aggarwal
Ankit Aggarwal

Reputation: 5375

queue your requests separately. So your response listeners will be separate for both the requests

call1.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Response<String> response) {
    }

    @Override
    public void onFailure(Throwable t) {
    }
});

and

call2.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Response<String> response) {
    }

    @Override
    public void onFailure(Throwable t) {
    }
});

Upvotes: 2

Related Questions