mariciucioan
mariciucioan

Reputation: 15

Retrofit2 onResponse changes does not persist

I have this code

public User getUser(final Context context, final Account user) {
        Call<List<User>> callUsers = request.getUsers(authKey, "json");
        callUsers.enqueue(new Callback<List<User>>() {

            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(context, String.valueOf(response.message()), Toast.LENGTH_LONG).show();
                    return;
                }

                List<User> users = response.body();

                for (User acc : users) {
                    if (acc.getUsername().equals(user.getUser())
                            || acc.getEmail().equals(user.getUser())) {
                        match = acc;
//                        String s = match.getId() + " " + match.getUsername() + " " + match.getEmail();
//                        Toast.makeText(context, s, Toast.LENGTH_LONG).show();
// Here the match contains the acc data
                    }
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
            }
        });

        String s = match.getId() + " " + match.getUsername() + " " + match.getEmail();
        Toast.makeText(context, s, Toast.LENGTH_LONG).show();
// Here match does not contain that data anymore...
        return match;
    }

So I want to receive some information from a REST API using retrofit2 and I want to store it in a variable called match if I find relevant data. It works fine within the onResponse method's body but when I try to return it at the end of my getUser method it does not contain the data anymore. How can I make that data persist ?

Upvotes: 0

Views: 53

Answers (1)

Droid
Droid

Reputation: 568

enqueue runs code within it asynchronously in a separate thread. Your program keeps executing after kicking off the enqueue request through retrofit and reaches the end of the function. Sometime later the api response returns with the data and runs the code inside the callback provided and terminates within the end of the callback body.

So first the program runs and enqueues your api request but continues till the return statement without adding anything to your variable and then later the api response returns data which populates the variable inside the callback. You have to wait for the api to return and assign your variable a value as it uses a callback.

Upvotes: 2

Related Questions