簡體   English   中英

Repository方法在Asynchronous Retrofit調用中設置LiveData值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM