๐ฑ dreaming DiNO
[Kotlin] ์ฝ๋ฃจํด How to return value from async coroutine scope such as ViewModelScope to your UI? ๋ณธ๋ฌธ
[Kotlin] ์ฝ๋ฃจํด How to return value from async coroutine scope such as ViewModelScope to your UI?
MK_____ 2023. 6. 26. 15:43How 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 ca...
stackoverflow.com
Another way without using LiveData would be like this,
Similar to viewModelScope there is also a lifecycleScope available with lifecycle-aware components, which can be used from the UI layer. Following is the example,
Fragment
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
findByID.setOnClickListener {
lifecycleScope.launch{
val res = usermodel.findbyID(et2.text.toString().toInt())
// use returned value to do anything.
}
}
}
ViewModel
//1st option
// make the function suspendable itself.use aync instead of launch and then
// use await to collect the returned value.
suspend fun findbyID(id: Int): userEntity {
val job = viewModelScope.async {
val returnedrepo = repo.delete(id)
Log.e(TAG,returnedrepo.toString())
return@async returnedrepo
}
return job.await()
}
//2nd option
// make the function suspendable itself. but switch the execution on IO
// thread.(since you are making a DB call)
suspend fun findbyID(id: Int): userEntity {
return withContext(Dispatchers.IO){
val returnedrepo = repo.delete(id)
Log.e(TAG,returnedrepo.toString())
return@withContext returnedrepo
}
}
Since LiveData is specific to Android Environment, Using Kotlin Flow becomes a better option in some places, which offers similar functionality.