簡體   English   中英

Android MVVM/Repository 如何強制 LiveData 從存儲庫更新?

[英]Android MVVM/Repository how to force LiveData to update from repository?

這是我的問題:

我使用過這樣的 MVVM/Repository 設計模式:

Activity -(Observes)-> ViewModel 的 LiveData -> Repository -> WebService API (GET Resource)

我有另一個要求將資源更新到 WebService 的電話。

問題:

更改服務器上的資源后。 我如何使資源livedata 使用新的服務器數據更新自身

我想強制它再次從服務器獲取數據,因為其他一些數據可能已更改。 而且我不想使用本地數據庫(房間)並更改它,因為我的服務器數據可能會更改。 他們每次都需要獲取。

我想到的唯一解決方案是為其創建一個 Livedata Source(作為 dataVersion)。 並在每次更新后增加它(偽代碼):

dataVersion = new MutableLiveData();
dataVersion.setValue(0);
// my repository get method hasnt anything to do with the dataVersion.
myData = Transformation.switchmap(dataVersion, versionNum -> { WebServiceRepo.getList() });

以及如何在 ViewModel 中更新 dataVersion。

您可以擴展MutableLiveData以為其提供手動獲取功能。

public class RefreshLiveData<T> extends MutableLiveData<T> {
    public interface RefreshAction<T> {
        private interface Callback<T> {
             void onDataLoaded(T t);
        }

        void loadData(Callback<T> callback);
    }

    private final RefreshAction<T> refreshAction;
    private final Callback<T> callback = new RefreshAction.Callback<T>() {
          @Override
          public void onDataLoaded(T t) {
               postValue(t);
          }
    };

    public RefreshLiveData(RefreshAction<T> refreshAction) {
        this.refreshAction = refreshAction;
    }

    public final void refresh() {
        refreshAction.loadData(callback);
    }
}

然后你可以做

public class YourViewModel extends ViewModel {
    private RefreshLiveData<List<Project>> refreshLiveData;

    private final GithubRepository githubRepository;
    private final SavedStateHandle savedStateHandle;

    public YourViewModel(GithubRepository githubRepository, SavedStateHandle savedStateHandle) {
         this.githubRepository = githubRepository;
         this.savedStateHandle = savedStateHandle;

         refreshLiveData = Transformations.switchMap(savedStateHandle.getLiveData("userId", ""), (userId) -> {
             githubRepository.getProjectList(userId);
         });
    }

    public void refreshData() {
        refreshLiveData.refresh();
    }

    public LiveData<List<Project>> getProjects() {
        return refreshLiveData;
    }
}

然后存儲庫可以執行以下操作:

public RefreshLiveData<List<Project>> getProjectList(String userId) {
    final RefreshLiveData<List<Project>> liveData = new RefreshLiveData<>((callback) -> {
         githubService.getProjectList(userId).enqueue(new Callback<List<Project>>() {
            @Override
            public void onResponse(Call<List<Project>> call, Response<List<Project>> response) {
                callback.onDataLoaded(response.body());
            }

            @Override
            public void onFailure(Call<List<Project>> call, Throwable t) {

            }
         });
    });

    return liveData;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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