【问题标题】:Type mismatch when getting the variable value from Repository in ViewModel从 ViewModel 中的 Repository 获取变量值时类型不匹配
【发布时间】:2018-11-05 19:16:27
【问题描述】:

我在 Android 上使用架构组件中的 LiveData 和 ViewModel。

这是我的存储库类 -

class DataRepository {

    var imagePath : String = ""
}

这是我的 ViewModel,我想在更新存储库中的值后从存储库中获取 imagePath 的值 -

class DataViewModel : ViewModel() {

    internal lateinit var imagePath : MutableLiveData<String>
    imagePath.value = DataRepository().imagePath

}

问题在于 DataRepository 中的 imagePathString 类型,而 DataViewModel 中的 imagePath 是 MutableLiveData 类型。

如何将存储库中的 imagePath 值分配给 ViewModel 中的值?我需要做任何类型转换吗?

【问题讨论】:

    标签: android kotlin android-architecture-components android-livedata android-viewmodel


    【解决方案1】:

    MutableLiveData 类中有一个方法:setValue。因此,你可以试试这个:

    internal lateinit var imagePath : MutableLiveData<String>
    imagePath.setValue(DataRepository().imagePath)
    

    【讨论】:

    • 谢谢。使用 LiveData 和 ViewModel 时是否总是需要使用 Room?因为我还没有看到 LiveData 和 ViewModel without Room 的教程
    • 如果不将数据存储到数据库(sqlite),则不需要使用Room
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2015-02-03
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多