0

I am trying to understand what will happen in case my activity isnt in scope when I get response for the retrofit query. I have a list of items in my activity, and I make a request to server and on response, update a few elements in the list. Below is the code.

I have the below retrofit dependency

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
            Call<Output> responseCall = APIInterface.getServerRequest(input);
            responseCall.enqueue(new Callback<Output>() {
                @Override
                public void onResponse(Call<Output> call, Response<Output> response) {
                     //update the data used by adapter.
                     adapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(Call<Output> call, Throwable t) {
                    //nothing much to do.
                }
            });

I have a few questions.

  1. When the onResponse/onFailure methods are called, are they called in the main UI thread, or are they still in the background thread?
  2. What will happen if my user has moved out of the existing activity, say they moved on to the next activity, or moved back to previous activity, or closed the app altogether. Will my onResponse still get called? And if my activity isnt on the stack and I refer to some variables in there, will I get nullPointerException?
  3. Is it possible, in the response method, to somehow get the reference to latest activity and then call the notifyDataSetChanged on the (maybe) new instance of activity?
Kraken
  • 23,393
  • 37
  • 102
  • 162

1 Answers1

0
  1. enqueue will do the request on a background thread but the callback will be called on the main thread.

  2. The request can return to an unavailable Activity/Fragment there are a few ways to mitigate problems.

    If the call is returning to an Activity you need to check if the Activity is still running. There are a few solutions here. Android: how do I check if activity is running?

    If the call is returning to a Fragment you can call isAdded() to check if you can mess with the Fragment.

  3. Not cleanly. But that shouldn't be a thing you want. If you want the request to end up in the new Activity then make the request in that Activity.

Here are a few resources:

If you want to set up a cancelable callback that will not return an output if its canceled. How to Cancel Retrofit request

If want the request to be lifecycle aware you use LiveData<Response<Output>> from your query. What are the benefits of returning a live data of a retrofit response

avalerio
  • 2,072
  • 1
  • 12
  • 11