我需要访问模型类中的sharedPrefences,因为我们不应该从模型类访问上下文和 View ,如何从模型中获取值?我不想将每个变量解析为 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
,不要 panic ,因为获取对 applicationContext 的静态引用不一定一定是 bad idea :
public class MyViewModel extends AndroidViewModel {
private val preferences: SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplication())
private val netManager: NetManager
private val model = CategoryModel(netManager, preferences)
...
}
现在更优雅的方式是使用 Factory
将依赖项注入(inject) 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, ..);
}
}
P.S:理想情况下,我会使用 ServiceLocator 或 DependencyInjector 创建模型,并将其直接注入(inject) ViewModel
使用提到的Factory
。
关于android - android-如何访问模型类 MVVM 中的上下文或共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55806684/