Search code examples
androidkotlinscopeviewmodelcoroutine

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
}

Solution

  • Thank you Nataraj KR for your Help!

    Following is the code that worked for me.

    View Model

    class ViewModel(application: Application):AndroidViewModel(application) {
    val TAG = "ViewModel"
    val repo: theRepository
    val alldata:LiveData<List<userentity>>
    val returnedVal = MutableLiveData<userentity>()
    init {
        val getDao = UserRoomDatabase.getDatabase(application).userDao()
        repo = theRepository(getDao)
        alldata = repo.allUsers
    
    }
    
    fun findbyID(id: Int){
        viewModelScope.launch {
           returnedVal.value = repo.findbyID(id)
        }
    }
    

    }

    Fragment

     override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    
        val usermodel = ViewModelProvider(this).get(ViewModel::class.java)
        usermodel.alldata.observe(this, Observer {
            Log.e(TAG,usermodel.alldata.value.toString())
        })
        usermodel.returnedVal.observe(this, Observer {
            tv1.text = usermodel.returnedVal.value.toString()
        })
    
        allData.setOnClickListener {
            tv1.text = usermodel.alldata.value.toString()
        }
    
        findByID.setOnClickListener {
            usermodel.findbyID(et2.text.toString().toInt())
        }
    }