Home > other >  Does block inside viewmodelscope runs on Main thread or background thread?
Does block inside viewmodelscope runs on Main thread or background thread?

Time:10-24

I recently checked the internal code of viewModelScope which is

CloseableCoroutineScope(SupervisorJob() Dispatchers.Main.immediate)

So my question is does the block inside the viewModelScope really runs on Main thread if yes, then how or which scope should I use to access or run DB operation inside view model? Because DB operation should run on background thread

CodePudding user response:

Coroutine launched using viewModelScope.launch {} by default runs on the Main Thread. If the DB operations are suspend (functions marked with suspend keyword) then it is safe to call them on the Main Thread:

val dao = ...

viewModelScope.launch {
    // DB operation
    dao.getItem() // Note: getItem() must be a `suspend` function
}

If DB operations are not suspend then you can use withContext(Dispatchers.IO) to switch context to Background Thread:

viewModelScope.launch {
    runDBInBackground()
}

suspend fun runDBInBackground() = withContext(Dispatchers.IO) {
    // DB operation
    dao.getItem() // Note: getItem() is a blocking function (not suspend)
}

CodePudding user response:

You can try the below code

     //If dao.getItem() is not suspend function
     viewModelScope.launch(Dispatchers.IO) {
          dao.getItem() 
     }


     //If dao.getItem() is suspend function
     viewModelScope.launch {
          dao.getItem() 
     }
  • Related