从 ViewModel 中的 Repository 获取变量值时类型不匹配

Type mismatch when getting the variable value from Repository in ViewModel

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

这是我的存储库 class -

class DataRepository {

    var imagePath : String = ""
}

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

class DataViewModel : ViewModel() {

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

}

问题是DataRepository中的imagePath类型为String,而DataViewModel中的imagePath类型为MutableLiveData.

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

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

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