Updated 29 April 2022
Before going to Asynchronous Programming In Kotlin let’s have a look at synchronous and asynchronous programming.
In synchronous operation/tasks are performed in a sequence.
One task has to wait for others to complete their execution and get a result.
The asynchronous programming technique allow the program to run while another task is executing.
In asynchronous multiple tasks executes parallelly.
It doesn’t execute in sequential order and doesn’t wait for another task to get completed.
In android, there is a single thread called “main thread” which manages everything.
The main thread is responsible for communication with android components and user interaction, and other tasks.
If we perform the long-running task on the main thread which may take 5 sec it will freeze the application.
Hence, the application gets crashed with the error message ANR( application not responding).To make the android app responsive it is essential to avoid performing long-running on the main thread.
Loading of components or operations related to DB or network are examples.
These types of operations need to be executed on another worker thread rather than the main thread.
Multithreading simply means performing several tasks parallelly without boking another task by running multiple threads.
There are many approaches like:
Threading
Callbacks
Futures, promises, and others
Coroutines
Reactive Extensions
Coroutines are lightweight threads.
Creating coroutines doesn’t allocate new threads, instead, they use predefine threads pools, that’s why coroutines are light weighted.
You can suspend and resume coroutine in mid-execution.
Suspend function is a function that can be paused, started, and resume.
We define suspend function using Suspend modifier.
They can only be called from a coroutine or another suspend function.
If you call directly then it will give an error.
Let’s consider an example.
In the below example, we are calling the delay function directly without coroutine scope which will give the below
1 2 3 4 5 6 7 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) delay(5000L)/*will give error-Suspend function 'delay' should be called only from a coroutine or another suspend function */ } |
So, now we will call the delay function from the global coroutine scope like:
1 2 3 4 5 6 7 8 9 10 11 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //using global coroutine scope. GlobalScope.launch { delay(5000L) // will work fine. } } } |
These are the functions that help to create a coroutine.
They can be called from normal functions because they are not suspended functions.
Below are the coroutine builders in Kotlin.
runBlocking : this blocks the current thread and waits for the coroutine to finish execution.
launch: start a coroutine in the background and keep working.
async: perform an asynchronous operation and return a deferred object. We can call await
on the deferred value in order to wait and get the result.
Define a scope/lifecycle for coroutines.
The lifecycle of a coroutine can be application-wide or bound to a component like Activity.
Coroutine builder is an extension of couroutineScope and inherits its context to propagate all its elements.
A dispatcher normally runs coroutines on threads. Every dispatcher is tied to a thread pool and manages to run coroutines on the threads.
There are majorly 4 types of Dispatchers.
Dispatcher.Main: It will start the coroutine in the main thread.
It is mostly used when needed to perform UI-related operations.
Like:
1 2 3 |
GlobalScope.launch(Dispatchers.Main) { println("Inside global scope, thred is:- "+Thread.currentThread().name.toString()) } |
Default Dispatcher: It starts the coroutine in the default thread.
It is used by all coroutine builders like launch, async, etc if no dispatcher specifies in the scope.
1 2 3 |
GlobalScope.launch(Dispatchers.Default) { println("Inside global scope, thread is:- "+Thread.currentThread().name.toString()) } |
IO Dispatcher: It is used to perform operations like networking, reading or writing the database, downloading files, etc.
1 2 3 4 |
GlobalScope.launch(Dispatchers.IO) { println("Inside global scope, thread is:- "+Thread.currentThread().name.toString()) } |
In this blog, we have learned about Synchronous and asynchronous programming and Coroutine in Kotlin.
To learn more about Coroutines, you can also refer to this link -> Guide
Thanks for Reading.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.