Android MVVM /存储库如何强制LiveData从存储库更新?

时间:2020-04-24 10:21:57

标签: java android mvvm repository-pattern android-livedata

这是我的问题:

我使用了如下的MVVM /存储库设计模式:

活动-(观察)-> ViewModel的LiveData->存储库-> WebService API(获取资源)

我还有一个呼吁更新 资源到WebService。

问题:

更改服务器上的资源后。我如何制作资源活动数据以使用新服务器数据进行自身更新

我想强制它再次从服务器获取数据,因为其他一些数据可能已更改。 而且我不想使用本地数据库(Room)并更改它,因为我的服务器数据可能已更改。并且他们每次都需要获取。

我唯一通过的解决方案是为它创建一个Livedata源(作为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。

1 个答案:

答案 0 :(得分:1)

您可以扩展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;
}