gpt4 book ai didi

android - android-如何在模型类 MVVM 中访问上下文或共享首选项

转载 作者:行者123 更新时间:2023-12-02 12:47:13 25 4
gpt4 key购买 nike

我需要在我的模型类中访问 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):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com