在浏览 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<>();
然后在改造异步调用中,我们设置该变量的值。
由于这是一个异步调用,该方法不会只返回初始化的数据,但从不返回设置的值吗?