android - andorid-如何在模型类 MVVM 中访问上下文或共享首选项
问题描述
我需要在我的模型类中访问 sharedPrefences,因为我们不应该从模型类访问上下文和视图,如何从模型中获取值?我不想解析我的每个变量viewmodel
,然后解析我的模型类。
模型类:
class CategoryModel(private val netManager: NetManager) {
var dateChanges: String = "null";
var isLoading= ObservableField<Boolean>(false)
fun getCats(): MutableLiveData<MutableList<Cat>> {
isLoading.set(true)
var list = MutableLiveData<MutableList<Cat>>();
if (netManager.isConnected!!) {
list = getCatsOnline();
}
return list
}
private fun getCatsOnline(): MutableLiveData<MutableList<Cat>> {
var list = MutableLiveData<MutableList<Cat>>();
val getCats = ApiConnection.client.create(Category::class.java)
Log.v("this","uid "+MyApp().uid)
getCats.getCats(MyApp().uid, dateChanges)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ success ->
isLoading.set(false)
list+= success.cats
},{
error->
isLoading.set(false)
Log.v("this","ErrorGetCats "+ error.localizedMessage);
}
)
return list;
}
operator fun <T> MutableLiveData<MutableList<T>>.plusAssign(values: List<T>) {
val value = this.value ?: arrayListOf()
value.addAll(values)
this.value = value
}
}
我该怎么做?
解决方案
首先你必须改变Model
类:
class CategoryModel(.. NetManager, private val sharedPrefences: SharedPrefences)
,现在您可以通过使用AndroidViewModel
而不是来获取 applicationContext ViewModel
,不要惊慌,因为获取对 applicationContext 的静态引用不一定是一个坏主意:
public class MyViewModel extends AndroidViewModel {
private val preferences: SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplication())
private val netManager: NetManager
private val model = CategoryModel(netManager, preferences)
...
}
现在一种更优雅的方法是使用 aFactory
将依赖项注入ViewModel
如下:
public static class Factory extends ViewModelProvider.NewInstanceFactory {
@NonNull
private final SharedPreferences mPreferences;
...
public Factory(@NonNull SharedPreferences preferences, ...) {
mPreferences = preferences;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
//noinspection unchecked
return (T) new MyViewModel(mPreferences, ..);
}
}
PS:理想情况下,我会使用ServiceLocator或DependencyInjector创建模型,并将其直接注入到ViewModel
使用提到的Factory
.
推荐阅读
- scala - 在 Scala 2.13 中将 Iterator 转换为 Iterable 的正确方法是什么?
- java - JDBC SQLite 如何判断数据库是否有活动连接
- python - 如何剪切或截断任何整数列值 - pandas
- angular - 如何通过检查元素的键来过滤数组中的元素
- python-3.x - python3 os 写入,结束文件
- java - 打印包含多个矩阵的数据文件
- c# - Asp.Net Core 5 使用应用程序部件注册控制器
- swift - Agora.io - 如何使用 mediaPlayer 共享视频时间戳?- iOS
- list - 带有列表的字典删除 u 刻度和括号
- php - 如何使用 Zend 将 UTF-8 BOM 包含到 CSV 导出中