-
Notifications
You must be signed in to change notification settings - Fork 22
Dispatchers Running on thread demo
Devrath edited this page Jan 14, 2024
·
3 revisions
-
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 itsEmpty co-routine-context
so worker. -
Main Dispatcher
is running on the main thread.
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}")
}
}
}
}
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