首页 > 解决方案 > 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
    }
}

我该怎么做?

标签: androidkotlinandroid-architecture-componentsandroid-viewmodelandroid-mvvm

解决方案


首先你必须改变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:理想情况下,我会使用ServiceLocatorDependencyInjector创建模型,并将其直接注入到ViewModel使用提到的Factory.


推荐阅读