I'm trying to retrieve a single entry from the Database and successfully getting the value back in my View Model with the help of viewModelScope, but I want this value to be returned back to the calling function which resides in the fragment so it can be displayed on a TextView. I tried to return the value the conventional way but it didn't work. So, How Can I return this value from viewModelScope.launch to the calling function?
View Model
fun findbyID(id: Int) {
viewModelScope.launch {
val returnedrepo = repo.delete(id)
Log.e(TAG,returnedrepo.toString())
// how to return value from here to Fragment
}
}
Repository
suspend fun findbyID(id : Int):userentity{
val returneddao = Dao.findbyID(id)
Log.e(TAG,returneddao.toString())
return returneddao
}
LiveData can be used to get value from ViewModel to Fragment . Make the function findbyID return LiveData and observe it in the fragment. fun findbyID(id: Int): LiveData</*your data type*/> { val result = MutableLiveData</*your data type*/>() viewModelScope. launch { val returnedrepo = repo.
For ViewModelScope , use androidx. lifecycle:lifecycle-viewmodel-ktx:2.4. 0 or higher. For LifecycleScope , use androidx.
A CoroutineScope defines a lifecycle, a lifetime, for Coroutines that are built and launched from it. A CoroutineScope lifecycle starts as soon as it is created and ends when it is canceled or when it associated Job or SupervisorJob finishes.
LiveData
can be used to get value from ViewModel
to Fragment
.
Make the function findbyID
return LiveData
and observe it in the fragment.
Function in ViewModel
fun findbyID(id: Int): LiveData</*your data type*/> {
val result = MutableLiveData</*your data type*/>()
viewModelScope.launch {
val returnedrepo = repo.delete(id)
result.postValue(returnedrepo)
}
return result.
}
Observer in Fragment
findbyId.observer(viewLifeCycleOwner, Observer { returnedrepo ->
/* logic to set the textview */
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With