🌱 dreaming DiNO
[Kotlin] 코루틴 How to return value from async coroutine scope such as ViewModelScope to your UI? 본문
Android
[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.
'Android' 카테고리의 다른 글
[Android] [문제 해결] 구글 플레이스토어에서 설치한 앱이 Signed APK 로 업데이트가 안되는 이유 (0) | 2023.07.06 |
---|---|
[adb] Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package [Package name] signatures do not match previously installed version (0) | 2023.06.26 |
[Kotlin] 안드로이드 코루틴 기본 개념과 활용 (0) | 2023.06.14 |
[Kotlin] ImageView 와 Memery leak (Bitmap 사용시) (0) | 2023.06.12 |
[Kotlin] 개발하면서 쓴 GroupBy, minByOrNull + a 정리 (0) | 2023.06.01 |