Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from async coroutine scope such as ViewModelScope to your UI?

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
}
like image 255
Arsal Avatar asked Mar 29 '20 06:03

Arsal


People also ask

How do I return a ViewModelScope value?

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.

How do I get ViewModelScope on my Android?

For ViewModelScope , use androidx. lifecycle:lifecycle-viewmodel-ktx:2.4. 0 or higher. For LifecycleScope , use androidx.

What is CoroutineScope in Kotlin?

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.


1 Answers

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 */
})
like image 56
Nataraj KR Avatar answered Sep 29 '22 12:09

Nataraj KR