简体   繁体   English

Repository方法在Asynchronous Retrofit调用中设置LiveData值

[英]Repository method sets LiveData value inside Asynchronous Retrofit call

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: 在浏览Android 体系结构组件的官方指南时,在使用Retrofit请求解释存储库层的部分中,有一段代码我似乎无法完全理解:

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: 在这个阶段,我们正在初始化我们的LiveData对象:

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? 由于这是一个异步调用,该方法不会只返回已初始化的数据,但从不使用值集吗?

You are correct that the LiveData instance will likely be returned from the method you show before the asynchronous network request completes. 您是正确的,可能会在异步网络请求完成之前从您显示的方法返回LiveData实例。

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. 请求完成后,该值将“输入”您返回的LiveData实例(这是对setValue的调用),然后将通知该实例的观察者。

AFAIK, you will create a method in the ViewModel class, which will return the method you mentioned above from the repository, something like LiveData<User>getUser() . AFAIK,您将在ViewModel类中创建一个方法,该方法将从存储库返回您上面提到的方法,例如LiveData<User>getUser() And because the Object returned from this function is wrapped in a LiveData you will be able to observe the changes in your Activity/Fragment: 并且因为从此函数返回的Object包含在LiveData您将能够观察Activity / Fragment中的更改:

 MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
    model.getUsers().observe(this, users -> {
        // update UI
    });

EDIT: 编辑:

Obviously the answer by @stkent is much more precise and gives a clear reason why the code works. 显然@stkent的答案更精确,并给出了代码有效的明确原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM