我需要访问模型类中的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
而不是ViewModel
来获取applicationContext,不要惊慌,因为获取对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
将依赖项注入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创建模型,并使用提到的ViewModel
将其直接注入Factory
。
我需要访问模型类中的sharedPrefences,因为我们不应该从模型类访问上下文和视图,如何从模型中获取值?
将其包装并作为依赖项传递给ViewModel
的构造函数。
包装它,它只是一个建议,以防你想从SharedPreferences
切换到其他东西来存储数据(EG。一个不同的库)
我将sharedPreferences包装为存储库,以便模型获得对此存储库接口的依赖,并且存储库实现获取其构造函数中的ApplicationContext