Search code examples
androidkotlinandroid-architecture-componentsandroid-livedataandroid-viewmodel

Type mismatch when getting the variable value from Repository in ViewModel


I'm using the LiveData and ViewModel from architecture components on Android.

This is my repository class -

class DataRepository {

    var imagePath : String = ""
}

This is my ViewModel where I want to get the value of imagePath from the repository after the value in the Repository has been updated -

class DataViewModel : ViewModel() {

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

}

The problem is that imagePath in the DataRepository is of type String and the imagePath in the DataViewModel is of type MutableLiveData.

How would I assign the imagePath value from repository to the one in ViewModel ? Do I need to do any type casting ?


Solution

  • There is a method: setValue in MutableLiveData class. Hence, you can try this:

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