Search code examples
android-roomkotlin-coroutines

Is CoroutineScope(SupervisorJob()) runs in Main scope?


I was doing this code lab https://developer.android.com/codelabs/android-room-with-a-view-kotlin#13 and having a question

class WordsApplication : Application() {
    // No need to cancel this scope as it'll be torn down with the process
    val applicationScope = CoroutineScope(SupervisorJob())

    // Using by lazy so the database and the repository are only created when they're needed
    // rather than when the application starts
    val database by lazy { WordRoomDatabase.getDatabase(this, applicationScope) }
    val repository by lazy { WordRepository(database.wordDao()) }
}
   private class WordDatabaseCallback(
       private val scope: CoroutineScope
   ) : RoomDatabase.Callback() {

       override fun onCreate(db: SupportSQLiteDatabase) {
           super.onCreate(db)
           INSTANCE?.let { database ->
               scope.launch {
                   var wordDao = database.wordDao()

                   // Delete all content here.
                   wordDao.deleteAll()

                   // Add sample words.
                   var word = Word("Hello")
                   wordDao.insert(word)
                   word = Word("World!")
                   wordDao.insert(word)

                   // TODO: Add your own words!
                   word = Word("TODO!")
                   wordDao.insert(word)
               }
           }
       }
   }

this is the code I found, as you can see, it is directly calling scope.launch(...) my question is that: isn't all the Room operations supposed to run in non-UI scope? Could someone help me to understand this? thanks so much!


Solution

  • Is CoroutineScope(SupervisorJob()) runs in Main scope?

    No. By default CoroutineScope() uses Dispatchers.Default, as can be found in the documentation:

    CoroutineScope() uses Dispatchers.Default for its coroutines.

    isn't all the Room operations supposed to run in non-UI scope?

    I'm not very familiar specifically with Room, but generally speaking it depends if the operation is suspending or blocking. You can run suspend functions from any dispatcher/thread. deleteAll() and insert() functions in the example are marked as suspend, therefore you can run them from both UI and non-UI threads.