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



这是我的问题:

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

活动-(观察(->ViewModel的LiveData->Repository->WebService API(GET Resource(

我有另一个调用,要求资源更新到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。

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

最新更新