5

在浏览 Android Architecture Components的官方指南时,在使用 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;
    }
}

在这个阶段,我们正在初始化我们的LiveData对象:

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

然后在改造异步调用中,我们设置该变量的值。

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

4

2 回答 2

2

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

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

于 2018-04-26T03:51:14.860 回答
2

AFAIK,您将在 ViewModel 类中创建一个方法,该方法将从存储库中返回您上面提到的方法,例如LiveData<User>getUser(). 并且因为从这个函数返回的对象被包裹在一个中,LiveData你将能够观察到你的 Activity/Fragment 的变化:

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

编辑:

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

于 2018-04-26T03:55:04.633 回答