I am building an app where I need to use Room database library. I have a specific thing to do - if an user enters some data, I need to store it in database and also update the UI to show it. Something like this -
fun insertAndShowData() {
// get relevant data
// launch a coroutine to store this data in the database
// update UI
}
What I understand is I need coroutines to do operations to database, but I'm not sure how to do it since I'm concerned that the coroutine might not finish before I update the UI, so the UI may not show the correct data. The examples on internet use either runBlocking
or GlobalScope.launch
, but it is mentioned that these are not recommended to use in a real application. Can someone tell me in detail how to do it, preferably with some code? I apologize in advance if I am asking very basic stuff since I am new to coroutines in Android.
CodePudding user response:
I suggest you to use the LiveData with Room, then you don't need to handle the "return" in order to update your view.
You still need to call your Room functions inside a coroutine (functions are suspend
)
For good practice, you can follow the codelabs (especially chapter 16) : https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0
CodePudding user response:
lifecycleScope.launch {
.....
}
CodePudding user response:
If the "update ui" code should be done only after the coroutine work is done, you can do this:
fun insertAndShowData() {
// get relevant data
lifecycleScope.launch {
withContext(Dispatchers.IO) {
//database operations here.
}
withContext(Dispatchers.Main) {
//update UI here.
}
}
}
CodePudding user response:
You need to use MutableLiveData and listen and bind that data on View. On the worker thread you can use postValue(T value) method. Therefore you listening LiveData on the main thread you are able to update the view.
https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData