【问题标题】:How to get the constructor argument in computed property如何在计算属性中获取构造函数参数
【发布时间】:2020-12-18 00:27:05
【问题描述】:

我将 sharedPreference 对象包装到 viewModel 中。

class MyViewModel @ViewModelInject constructor(
    application: Application,
    myPreferences: MyPreference
) : AndroidViewModel(application) {

    private val viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }

    private val _something: String
        get() = myPreferences.getStoredSomething(getApplication()) // But myPreferences can not be used in this line.
    val something = MutableLiveData<String>()
}

如何固定myPreferences的作用域到达构造函数?

【问题讨论】:

    标签: android kotlin computed-properties


    【解决方案1】:

    您可以使用valvar 在主构造函数中声明类属性,并可选择添加访问修饰符。它将使您的构造函数参数成为属性,并且它们将在您的类中可用,就好像您在 private val viewModelJob... 属性附近声明它们一样。

    这是一个修改了主构造函数的例子,它的参数声明为private val。现在它们在这个类的整个范围内都是可见的。

    class MyViewModel @ViewModelInject constructor(
        private val application: Application,
        private val myPreferences: MyPreference
    ) : AndroidViewModel(application) {
    
        ... 
    
        private val _something: String
            get() = myPreferences.getStoredSomething(getApplication())
    
        val something = MutableLiveData<String>()
    }
    

    此特定功能的官方示例 (source link):

    ...对于声明属性并从主构造函数初始化它们,Kotlin 有一个简洁的语法:

    class Person(val firstName: String, val lastName: String, var age: Int) { /*...*/ }
    

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多