android - LiveData、MVVM 和存储库模式
问题描述
这是一个好方法还是我刚刚找到了一个讨厌的解决方法?
我正在使用MediatorLiveData
类,因为似乎对更新LiveData
对象的源很有用。
我的意思是,我在互联网上找到的大多数教程都只是使用Livedata
或MutableLivedata
不使用动态源,例如:
fun search(/*no input params*/): Call<List<Person>>
但就我而言,我有以下按名称执行搜索的 Web 服务:
interface APIServidor {
@GET("search")
fun search(@Query("name") name: String): Call<List<Person>>
}
public class PeopleRepository {
public LiveData<List<Person>> search(String name){
final MutableLiveData<List<Person>> apiResponse = new MutableLiveData<>();
Call<List<Person>> call = RetrofitService.Companion.getInstance().getApiServer().search(name);
call.enqueue(new Callback<List<Person>>() {
@Override
public void onResponse(@NonNull Call<List<Person>> call, @NonNull Response<List<Person>> response) {
if (response.isSuccessful()) {
apiResponse.postValue(response.body());
}
}
@Override
public void onFailure(@NonNull Call<List<Person>> call, @NonNull Throwable t) {
apiResponse.postValue(null);
}
});
return apiResponse;
}
}
然后在 viewmodel 类中,我为每个新请求添加源。
public class SearchViewModel extends ViewModel {
private MediatorLiveData<List<Person>> mApiResponse;
private PeopleRepository mApiRepo;
public SearchViewModel() {
mApiResponse = new MediatorLiveData<>();
mApiRepo = new PeopleRepository();
}
public LiveData<List<Person>> getPlayers() {
return mApiResponse;
}
public void performSearch(String name){
mApiResponse.addSource(mApiRepo.search(name), new Observer<List<Person>>() {
@Override
public void onChanged(List<Person> apiResponse) {
mApiResponse.setValue(apiResponse);
}
});
}
}
活动
bt_search.setOnClickListener {
val player_name = et_player.text.toString()
viewModel.performSearch(player_name)
}
项目范围
我在一个个人项目中
目标
使用 MVVM + 实时数据 + 存储库模式
问题
我只找到了一种简单方法的教程:观察一个LiveData
访问repository
对象并只获取一次数据的对象。
select * from people
例如:从 Web 服务获取所有人 ( )。
select * from people where name=?
我的案例:从 Web 服务中获取具有姓名 ( ) 的人。
https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890 https://medium.com/@sriramr083/error-handling-in-retrofit2-in -mvvm-repository-pattern-a9c13c8f3995
怀疑
对用户输入MediatorLiveData
的所有请求使用类是个好主意吗?merge
我应该使用MutableLiveData
和更改repository
课程并使用自定义的clousure吗?
有更好的方法吗?
解决方案
我也将这种模式与 MediatorLiveData 一起使用,但它形成了一个问题。从用户的角度来看,它似乎运行得很好,但这里的一个问题是每次调用performSearch()
存储库时都会创建一个新的 LiveData 对象,该对象还会通过addSource()
.
一个想法可能是让存储库只创建一次 MutableLiveData 对象,并在连续调用时更新它的值。所以 feMutableLiveData<List<Person>> apiResponse;
将是一个未初始化的私有字段,在search()
方法中被初始化。
例如。if (apiResponse == null) apiResponse = new MutableLiveData();
推荐阅读
- image-processing - 在 Keras 图像分类中不会减少的损失验证
- sql - 如何在 SQL 中合并数据
- sql - SQL 连接查询具有跨 3 个表的列总和的视图
- git-bash - Git Bash - 开始时带有“/”的字符串参数正在扩展为文件路径。如何阻止这种情况?
- laravel - Laravel 使用 $request 中的 where 子句和 like 连接数据库表
- azure - 从 PowerShell 部署 LogicApp
- r - 如何选择 group_by 之后未汇总的列?
- google-apps-script - 如何修改当前插入时间戳脚本以在清除单元格时删除时间戳
- c# - .Net Core - 实体框架核心迁移 - 生产
- javascript - 防止 amcharts 系列重叠