I'm trying to migrate my code from RxJava2 to Coroutines. But I'm not sure how to achieve that.
For example, this is my old code to insert a code into the Room Database:
fun insert(note: Note) = Single.fromCallable {
dao.insert(note)
}.subscribeIn({ id ->
note.id = id
if (note.bitmap != null) update(note)
}
Note: This code is in an object called DataHelper, which contains all the methods and the Dao object.
This is the Dao Call:
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(note: Note): Long
Trying to replace that code with coroutine calls isn't clear, as I can't call a suspend function from the main thread.
fun insert(note: Note) {
val id = withContext(Dispatchers.IO) {
dao.insert(note)
}
note.id = id
if (note.bitmap != null) update(note)
}
dao.insert() is now a suspend function in the Dao.
Making the insert(Note) function a suspend function means I have to call it with a Dispatcher from any place (E.g, a fragment). Which either means there has to be a Dispatcher in every fragment or activity, or having the whole line of calls suspended.
What is the right way to run background threads with Coroutines?
CoroutineContextof every activity/fragment then useGlobalScopeto call your function in insert method, although it's not best practice to do.