Issue
this method runs a database operation (returns a generated ID) and must be on background thread:
fun insert(note: Note): Long{
return noteDao.insert(note)
}
Is there a way to implement it using RX / Coroutines? (without using the suspend
keyword)
I currently use AsyncTask:
override fun insert(note: Note): Long {
return InsertTask(this, noteDao).execute(note).get()
}
private class InsertTask(noteRepository: NoteRepository, private val noteDao: NoteDao) : AsyncTask<Note, Void, Long>() {
override fun doInBackground(vararg note: Note): Long {
return noteDao.insert(note[0])
}
override fun onPostExecute(generatedId: Long) {
getTheId(generatedId)
}
private fun getTheId( id: Long): Long {
return id
}
}
Solution
With coroutines, it's pretty easy. But you will need coroutines support for Room
.
Gradle dependency:
implementation "androidx.room:room-ktx:2.1.0"
Next, mark your methods in dao as suspend.
@Insert
suspend fun insert(note: Note): Long
I don't know how much info you have about coroutines, but it goes like that:
aCoroutineScope.launch(Dispatchers.IO){
//to make analogy you are inside the do in backgroun here
val id = dao.insert(note)
withContext(Dispatchers.Main){
//oh well you can call this onPostExecute :)
//do whatever you need with that selectId here
handleIdOnTheMainThread(id)
}
}
But I do insist not to use it with 0 information about coroutines.
About RxJava:
Room has also support for Rx, so please refer to this link.
Answered By - coroutineDispatcher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.