Skip to content

Dispatchers Running on thread demo

Devrath edited this page Jan 14, 2024 · 3 revisions

banner-3-1920x600

Observations

  • Empty co-routine-context is running on the worker thread.
  • View-model scope is running on the main thread.
  • Default is running on the worker thread.
  • IO is running on the worker thread.
  • Unconfined is running on the worker thread because it depends on the enclosing scope currently its Empty co-routine-context so worker.
  • Main Dispatcher is running on the main thread.

Code

class DispatchersDemoVm @Inject constructor( ) : ViewModel() {

    // Create a root co-routine scope
    private val rootScope =  CoroutineScope(EmptyCoroutineContext)


    fun demo() {

        rootScope.launch() {
            println("Empty co-routine-context Executes on thread -> ${Thread.currentThread().name}")
        }

        viewModelScope.launch {
            println("View-model-scope executes onExecutes on thread -> ${Thread.currentThread().name}")
        }

        viewModelScope.launch(Dispatchers.Main) {
            println("View-model-scope + Main, executes onExecutes on thread -> ${Thread.currentThread().name}")
        }

        viewModelScope.launch(Dispatchers.Default) {
            println("View-model-scope + Default, executes onExecutes on thread -> ${Thread.currentThread().name}")
        }

        viewModelScope.launch(Dispatchers.IO) {
            println("View-model-scope + IO, executes onExecutes on thread -> ${Thread.currentThread().name}")
        }

        rootScope.launch {
            viewModelScope.launch(Dispatchers.Unconfined) {
                println("View-model-scope + Unconfined, executes onExecutes on thread -> ${Thread.currentThread().name}")
            }
        }
    }
}

Out-put

Empty co-routine-context Executes on thread -> DefaultDispatcher-worker-1
View-model-scope executes onExecutes on thread -> main
View-model-scope + Default, executes onExecutes on thread -> DefaultDispatcher-worker-2
View-model-scope + IO, executes onExecutes on thread -> DefaultDispatcher-worker-1
View-model-scope + Unconfined, executes onExecutes on thread -> DefaultDispatcher-worker-2
View-model-scope + Main, executes onExecutes on thread -> main
Clone this wiki locally