Skip to content

Dispatchers Running on thread demo

Devrath edited this page Jan 13, 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 on Executes on thread -> ${Thread.currentThread().name}")
        }

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

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

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

    }

}

Out-put

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