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

标签 android kotlin android-architecture-components android-viewmodel android-mvvm

我需要访问模型类中的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:理想情况下,我会使用 ServiceLocatorDependencyInjector 创建模型,并将其直接注入(inject) ViewModel使用提到的Factory

关于android - android-如何访问模型类 MVVM 中的上下文或共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55806684/

相关文章:

android - 导入外部jar和Gradle错误

对话框中的 Android Maps API v2

android - Android 房间交易如何完成返回

Android Adob​​e Reader - 显示来自网络的 PDF

android - 如何连接到 rild 套接字

android - 使用协程 api 获取实体

kotlin - 减少/折叠中的两个累加器

android - Jackson Mixins 与 Kotlin

android - 使用 Room 加入查询

android - 如何实现 LiveData 单例