Android 存储库方法在异步改造调用中设置LiveData值

Android 存储库方法在异步改造调用中设置LiveData值,android,retrofit2,android-architecture-components,user-guide,Android,Retrofit2,Android Architecture Components,User Guide,在阅读Android的官方指南时,在解释带有改装请求的存储库层的部分,有一段代码我似乎无法完全理解: public class UserRepository { private Webservice webservice;     // ...     public LiveData<User> getUser(int userId) {         // This is not an optimal implementation, we'll fix it below

在阅读Android的官方指南时,在解释带有改装请求的存储库层的部分,有一段代码我似乎无法完全理解:

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;
    }
}
然后在改造异步调用中,我们设置该变量的值


由于这是一个异步调用,该方法是否只返回已初始化的数据,而不返回已设置的值?

在异步网络请求完成之前,
LiveData
实例可能会从所显示的方法返回,这是正确的


如果将网络请求排队不足以阻止其符合垃圾收集的条件,那么这将是一个问题。由于情况并非如此,因此在退出方法后,网络请求将继续执行。请求完成后,该值将“输入”您返回的
LiveData
实例(这是调用
setValue
所做的),然后将通知该实例的观察者。

AFAIK,您将在ViewModel类中创建一个方法,该方法将从存储库返回上述方法,类似于
LiveDatagetUser()
。由于此函数返回的对象包装在
LiveData
中,因此您将能够观察活动/片段中的变化:

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


显然,@stkent的答案要精确得多,并且给出了代码工作的明确原因。

我只是好奇,你到底做了些什么,为同样的代码编写了单元测试
 MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
    model.getUsers().observe(this, users -> {
        // update UI
    });