java - 如何从 MVVM 架构中的 Web 服务的存储库类与活动/片段进行通信
问题描述
我是新手MVVM architecture
,我只想知道如何在和之间进行通信repository class
。UI (activity/fragment) class
我遇到了正在做这项工作以进行更新的实时数据same entities from both (remote and room database)
。
例如:1)如果我有名为用户的实体。我可以使用如下实时数据保存并观察它:(来自 android 开发者网站)。
public class UserRepository {
private final Webservice webservice;
private final UserDao userDao;
private final Executor executor;
@Inject
public UserRepository(Webservice webservice, UserDao userDao, Executor executor) {
this.webservice = webservice;
this.userDao = userDao;
this.executor = executor;
}
public LiveData<User> getUser(String userId) {
refreshUser(userId);
// Returns a LiveData object directly from the database.
return userDao.load(userId);
}
private void refreshUser(final String userId) {
// Runs in a background thread.
executor.execute(() -> {
// Check if user data was fetched recently.
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
if (!userExists) {
// Refreshes the data.
Response<User> response = webservice.getUser(userId).execute();
// Check for errors here.
// Updates the database. The LiveData object automatically
// refreshes, so we don't need to do anything else here.
userDao.save(response.body());
}
});
}
}
2)但是我们如何在不需要实时数据但我只想显示或隐藏进度对话框的其他 API 中做到这一点(登录)取决于网络成功或错误消息。
public void isVerifiedUser(int userId){
executor.execute(() -> {
// making request to server for verifying user
Response<User> response = webservice.getVerifyUser(userId).execute();
// how to update the UI like for success or error.
//update the progress dialog also in UI class
});
}
解决方案
您需要isVerifiedUser()
返回一个 liveData,您可以在与该 UI(活动/片段)相关的 viewModel 中观察它。
1.内部存储库:
public LiveData<State> isVerifiedUser(int userId){
MutableLiveData<State> isVerified = new MutableLiveData();
executor.execute(() -> {
Response<User> response = webservice.getVerifyUser(userId).execute();
// Update state here.
isVerified.postValue(valueHere)
});
return isVerified;
}
2.视图模型:
public ViewModel(final Repository repository) {
//observe userId and trigger isVerifiedUser when userId value is changed
stateLiveData = Transformations.map(userId, new Function<>() {
@Override
public RepoMoviesResult apply(Integer userId) {
return repository.isVerifiedUser(userId);
}
});
}
3.活动:
viewModel.getStateLiveData ().observe(this, new Observer<>() {
@Override
public void onChanged(State state) {
//do something here
}
});
更多信息:
推荐阅读
- kaggle - Kaggle API 令牌未下载
- huggingface-transformers - Rasa 与 HuggingFace 的集成管道
- javascript - 如何在单击时将函数中的变量作为全局变量返回
- performance - 如何去除 Faster RCNN 中的误检(误报)
- oracle - 在Snowflake sql中我们可以调用Oracle的Sequence函数吗
- powershell - GCloud powershell 命令抛出错误,但在 cmd 中工作正常
- macos - 有没有办法在 Mac vi 编辑器中选择所有过滤后的字符串?
- python - 按具体日期排序?数字?列表中包含的列表
- javascript - 如何在 Vue3 compositionAPI 中触发 $forceUpdate?
- wordpress - 自定义 WordPress PHP 代码以在帖子中显示其他帖子破坏了我的评论