Getting Started With Coroutines In Kotlin
23 July, 2021
2
2
0
Contributors
Implementing Long-running Operations/Tasks From The Main Thread Leads to Freezes And Unresponsiveness In Your Application.
Background Threads Are To Handle Long-running Operations/Tasks While The Main Thread Continues To Handle UI Updates.
Coroutines can be imagined as lightweight threads, but several important differences make their real-life usage very different from threads.
Note:
You Need To Import import kotlinx.coroutines.*
To Get Started With Coroutines.Run the Above code to get to your first working coroutine.
launch
is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work independently. That's why Stay
is printed first
.delay
is a special suspending function. It delays the coroutine for a specific time [That Specific Time Should Be Provided In delay's parentheses (delay time in ms)
]. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.runBlocking
is also a coroutine builder that connects the non-coroutine code of a regular fun main()
and the code with coroutines inside of runBlocking { ... }
curly braces. This is highlighted in an IDE(s) by this: CoroutineScope
hint, immediately after the runBlocking opening curly bracket.Remove or Skip runBlocking
in this code, you'll get an error on the launch call, since launch is declared only in the CoroutineScope
.CoroutineScope?
In Short:
scope Provides lifecycle methods for coroutines and allows us to start and stop coroutines.launch
, async
, etc) is an extension on CoroutineScope
and inherits its coroutineContext to, automatically generates all its elements and cancellation
.coroutineScope { } As Well
Beside's launch
and runBlocking
.Coroutines In Android
🤔?Make Sure
That You Have Included Coroutines Dependency If It's Not Included:GlobalScope.launch{ }
In Your Main Thread Or Any Other Coroutine:Note:
You Should NOT
Use GlobalScope every time.Log
In Our Coroutine:Log Is Executing In
Background Thread
.Note:
In Your Logcat, Dispatcher Worker's Numerical May Differ[Don't Worry About That].Log Is Executing In
Background Thread
.Note:
In Your Logcat, Dispatcher Worker's Numerical May Differ[Don't Worry About That].->Play Around With delay()
In The Coroutine😉
Bye🤗
android
threads
coroutines
kotlin