27
loading...
This website collects cookies to deliver better user experience
Make Sure
That You Have Included Coroutines Dependency If It's Not Included:implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
Launches With A Specific Context
And This Context Will Describe That In Which A Specific Thread/Coroutine Will Launch In
.GlobalScope.launch{ }
To Launch A New Coroutine Which Doesn't Give Full Flexibility Which We Want.Dispatchers
Dispatchers Determine What thread or threads the corresponding coroutine uses for its execution.
launch
and async
accept an optional CoroutineContext parameter that can be used to explicitly specify the dispatcher for the new coroutine.1
. Dispatchers.Main
: Main
Dispatcher Allows Us To Control UI Elements From A Coroutine Which Will Be Executed As The Main Thread From A Coroutine Itself. GlobalScope.launch(Dispatchers.Main) {
//Code
}
Log
To Check Whether Main
Dispatcher Is Running In MainDispatcher Or Not:GlobalScope.launch(Dispatchers.Main) {
Log.d("mainCoroutine","Running In ${Thread.currentThread().name}")
}
Main
Dispatcher As We Declared It As Main Dispatcher.Control UI
After Specifying Main
Dispatcher🤔?For Controlling UI
From A Coroutine After Specifying Main Dispatcher
.Main
*Dispatcher * So That I Can Work With UI.Main
Dispatcher If You Want To Control UI Elements From A Coroutine, You'll Get This Beautiful Error In Your Logcat After Launching The Application Which Says:This Error Occurs If You Didn't Mention It As Main
Dispatcher. Because UI Elements Can Be Controlled Only From The Main Thread.
2
. Dispatchers.IO
: IO
Dispatcher Is Used To Control || Execute All Those Data Operations
Such As Networking, Writing/Adding Data In Database(s), Reading || Writing The Files.GlobalScope.launch(Dispatchers.IO) {
//Code
}
3
. Dispatchers.Default
: Default
Dispatcher Can Be Used To Run Long Operations
|| Long Tasks Which Will Make Main Thread As A Unresponsiveness. To Avoid Unresponsiveness In Your App, You Can Use Default
Dispatcher.GlobalScope.launch(Dispatchers.Default) {
//Code
}
4
. Dispatchers.Unconfined
: Unconfined
Dispatcher Is Not Confined To Any Specific Thread. In Other Words, The Unconfined Dispatcher Is Appropriate For coroutines That Neither Consume CPU Time Nor Update Any Shared Data (like UI) Confined To A Specific Thread.GlobalScope.launch(Dispatchers.Unconfined) {
//Code
}
Yes
, It's Possible:Log
So That We'll Be Knowing That Is These Really Executing In Coroutine Dispatcher's Or Not.
GlobalScope.launch {
delay(1000L)
launch(Dispatchers.Main) {
Log.d("multipleLaunches", "Running In ${Thread.currentThread().name}")
}
delay(1000L)
launch(Dispatchers.IO) {
Log.d("multipleLaunches", "Running In ${Thread.currentThread().name}")
}
delay(1000L)
launch(Dispatchers.Default) {
Log.d("multipleLaunches", "Running In ${Thread.currentThread().name}")
}
delay(1000L)
launch(Dispatchers.Unconfined) {
Log.d("multipleLaunches", "Running In ${Thread.currentThread().name}")
}
}
Bye🤗