[英]Android - MVVM with LiveData component and a Retrofit call in Repository
[英]Repository method sets LiveData value inside Asynchronous Retrofit call
在瀏覽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;
}
}
在這個階段,我們正在初始化我們的LiveData
對象:
final MutableLiveData<User> data = new MutableLiveData<>();
然后在改進的異步調用中,我們設置該變量的值。
由於這是一個異步調用,該方法不會只返回已初始化的數據,但從不使用值集嗎?
您是正確的,可能會在異步網絡請求完成之前從您顯示的方法返回LiveData
實例。
如果排隊網絡請求不足以阻止其符合垃圾收集條件,則會出現問題。 由於情況並非如此,因此退出方法后網絡請求將繼續執行。 請求完成后,該值將“輸入”您返回的LiveData
實例(這是對setValue
的調用),然后將通知該實例的觀察者。
AFAIK,您將在ViewModel類中創建一個方法,該方法將從存儲庫返回您上面提到的方法,例如LiveData<User>getUser()
。 並且因為從此函數返回的Object包含在LiveData
您將能夠觀察Activity / Fragment中的更改:
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
編輯:
顯然@stkent的答案更精確,並給出了代碼有效的明確原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.