Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repository method sets LiveData value inside Asynchronous Retrofit call

Tags:

When going through the official guide for the Android Architecture Components, in the section that explains the repository layer with a Retrofit request there is a piece of code I cannot seem to fully understand:

public class UserRepository {
    private Webservice webservice;
    // ...
    public LiveData<User> getUser(int userId) {
        // This is not an optimal implementation, we'll fix it below
        final MutableLiveData<User> data = new MutableLiveData<>();
        webservice.getUser(userId).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                // error case is left out for brevity
                data.setValue(response.body());
            }
        });
        return data;
    }
}

At this stage we are initializing our LiveData object:

final MutableLiveData<User> data = new MutableLiveData<>();

Then in the retrofit asynchronous call, we set the value for that variable.

As this is an asynchronous call, wouldn't that method just return the data initialized but never with the value set?

like image 498
Juan Manuel Amoros Avatar asked Apr 26 '18 00:04

Juan Manuel Amoros


1 Answers

You are correct that the LiveData instance will likely be returned from the method you show before the asynchronous network request completes.

This would be a problem if enqueuing a network request was not sufficient to prevent it from being eligible for garbage collection. Since this is not the case, the network request will continue to execute after you exit your method. Once the request completes, the value will be "fed into" the LiveData instance that you returned (this is what the call to setValue does), and observers of that instance will then be notified.

like image 185
stkent Avatar answered Sep 28 '22 07:09

stkent