Home > Net >  Android View Model passing parameter
Android View Model passing parameter

Time:10-13

I am new in Kotlin and try to make an app with Jetpack Compose and need help to following problem:

In my DAO, I created the following Query:

@Query("SELECT * FROM GrungeInfoDbModel WHERE infoname = :infoname")
fun getInfoGrunge(infoname: String): GrungeInfoDbModel

Declared it in Repository:

interface Repository {

    fun getAllGrunges(): LiveData<List<GrungeModel>>

    fun getAllGrungeInfos(): LiveData<List<GrungeInfoModel>>

    fun getGrungeInfo(infoname: String): LiveData<GrungeInfoModel>
}

RepositoryImpl:

    override fun getGrungeInfo(infoname: String): LiveData<GrungeInfoModel> = grungeInfoLiveData

The problem is now: How can I pass the parameter infoname to my ViewModel:

    val grungeInfoByInfoname by lazy { repository.getGrungeInfo(**here should be the parameter infoname) }

Thanks for your help!

CodePudding user response:

Referring to the android dev documentation, you can do the following inside your ViewModel:

private val infonameInput = MutableLiveData<String>()
val grungeInfo: LiveData<GrungeInfoModel> = Transformations.switchMap(infonameInput) { infoname -> 
    repository.getGrungeInfo(infoname) 
}

private fun setInfonameInput(infoname: String) {
    infonameInput.value = infoname
}
  • Related