Skip to content

Dispatchers Running on thread demo

Devrath edited this page Jan 14, 2024 · 3 revisions

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.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-1
View-model-scope + IO, executes onExecutes on thread -> DefaultDispatcher-worker-2
View-model-scope + Unconfined, executes onExecutes on thread -> DefaultDispatcher-worker-1

Clone this wiki locally