Reputation: 1081
I'm new to Retrofit 2.0. I'm making a standard call to get the data back:
final Call<HomeFeedContainer> call = service.getHomeFeed(token, placement);
call.enqueue(new Callback<HomeFeedContainer>() {
@Override
public void onResponse(Call<HomeFeedContainer> call, Response<HomeFeedContainer> response) {
//stuff
}
@Override
public void onFailure(Call<HomeFeedContainer> call, Throwable t) {
//stuff
}
});
I noticed that the call completes successfully even if I suspend/kill the application. I would like to use call.cancel() when this happens, but I don't have access to this local object in onPause(). If I make Call a member of my class, I can certainly cancel the call in onPause(), but I can't use the Call object to make another call. I'll have to set this to a new Call object if I want to make the call again. This doesn't seem like the right approach.
How should I be handling my Call objects when the user suspends the app? Thx.
Upvotes: 0
Views: 885
Reputation: 4199
Instead of cancelling the ongoing api call. Use a boolean value to check whether app is in background or not.
Check if app is background or foreground : Link
final Call<HomeFeedContainer> call = service.getHomeFeed(token, placement);
call.enqueue(new Callback<HomeFeedContainer>() {
@Override
public void onResponse(Call<HomeFeedContainer> call, Response<HomeFeedContainer> response) {
//stuff
if(appForground){
//do stuff related to UI and all
}
}
@Override
public void onFailure(Call<HomeFeedContainer> call, Throwable t) {
//stuff
}
});
UPDATE : If you want to cancel an ongoing Retrofit API call you can use call.cancel().
When u call cancel() onFailure() method gets executed. you can use isCancelled() to check whether api call was cancelled or the device has no internet connection. for more details visit : Link
Upvotes: 1