Updated March 31, 2023
Introduction to Kotlin Coroutines
The kotlin coroutines are one of the features that can be used for to convert the async callbacks for long-running tasks that include the database, network access into the sequential code; the long-running tasks are the main tasks that take too long on to block the main thread and also the main safety is to allow for to ensure that any suspend function is called from the main thread so the coroutine itself the code block that can be passed to the live data builder as the parameter also each object that will run the coroutine when it’s observed.
Syntax:
In kotlin language has many default packages, so that we include some advanced packages and features like coroutine. So we have imported coroutine using Kotlinx jars based on that the classes and methods are called upon the code.
import kotlinx.coroutines.*
fun main() = runBlocking { // It’s the CoroutineScope
launch{ // default method for creating coroutine and continue the task
delay(values) // default methods for blocking and non-blocking delays
}
The above code is the basic syntax for to creating and assigning the coroutine in the kotlin codes. We used default methods for to utilising the coroutine type tasks.
How do Coroutines work in Kotlin?
- The coroutine is one of the types of instance, and it is the suspendable computation for concepts like similar to threads in the sense that it takes a block of codes that run continuously works with the rest of the code. Like the coroutine, the particular thread may suspend its execution flow in the one level of the thread, and it resumes in another thread.
- Generally, coroutines can be thought of like light-weight threads, but there is a number of important differences that make their real-life usages different from the threads. We used default methods like launch(), and delay() is the coroutine builder for to create the coroutine concurrently execute the rest of the code, which continues to work independently each other.
- The delay() is the suspending function; it suspends the coroutine for a specific time. Suspending the coroutine does not block the underlying thread but allows other coroutines to run and use the underlying thread for their code. Similarly, the runBlocking is the coroutine builder that bridges the non-coroutine world of the regular scope using opening and closing braces. When we use thread in the application, it has creation, execution, and blocking for the duration of the call until all the coroutines are inside the open and closed brackets.
Examples of Kotlin Coroutines
Given below are the examples of Kotlin Coroutines:
Example #1
Code:
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.*
suspend fun demo(){
println("The Suspended function used for to access and un-access the datas which is alreday decalred by the user end")
val a = listOf('A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
println(a.size)
println(a.indexOf(23))
println(a[14])
for(j in a.indices){
println(a[j])
}
}
suspend fun firstExample() = coroutineScope {
launch {
delay(23L)
val x = listOf("January is the first month", "February is the second month", "March is the third month", "April is the fourth month", "May is the fifth month", "June is the sixth month", "July is the seventh month", "August is the eigth month", "September is the nineth month", "October is the tenth month", "November is the eleventh month", "December is the twelth month")
println("The month details are: $x")
for(j in x.indices){
println(x[j])
}
val b = listOf("Tv is first electrical appliance","Fridge is the second appliance","Washing machine is third appliance", "Fridge is fourth appliance", "Laptop is fifth appliance", "PC is sixth appliance", "Microwave oven is seventh appliance", "Ups-Inverter is eigth appliance", "Mobile is electronic device","Fan is tenth appliance")
val res = b.get(6)
println(res)
val res1 = b[3]
println(res1)
val out1 = b.indexOf("Laptop")
println("The first index of number is $out1")
val out2 = b.lastIndex
println("The last index of the list is $out2")
}
println("Tke kotlin coroutine packages are successfully created and utilised in the application")
}
fun main(args: Array<String>) = runBlocking{
println("Welcome To My Domain its the first example that related to the kotlin coroutine")
launch(CommonPool) {
delay(32)
demo()
println("Have a Nice day users please try again")
}
println("The values are entered using the coroutine packages")
firstExample()
}
Output:
In the above example, we used coroutine classes with the collection feature.
Example #2
Code:
import kotlinx.coroutines.*
fun secondExample(str: String) = println("[${Thread.currentThread().name}] $str")
fun main() = runBlocking<Unit> {
launch {
println("Its the main runBlocking thread ${Thread.currentThread().name}")
val a = launch {
delay(23L)
println("First Launch!")
}
a.join()
repeat(23) {
launch {
delay(12L)
}
}
}
launch(Dispatchers.Unconfined) {
println("The second launch thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) {
println("The third launch thread ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("string")) {
println("The fourth launch thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
println("The fifth launch thread ${Thread.currentThread().name}")
delay(24)
println("The fifth launch after delaying thread ${Thread.currentThread().name}")
}
launch {
println("The sixth launch thread ${Thread.currentThread().name}")
delay(34)
println("The sixth launch after delaying thread ${Thread.currentThread().name}")
}
val x = async {
secondExample("String value1")
4
}
val y = async {
secondExample("String value2")
3
}
secondExample("The state is awaiting section ${x.await() * y.await()}")
}
Output:
In the second example, we created launch{} blocks with some async thread execution.
Example #3
Code:
import kotlinx.coroutines.*
import java.text.SimpleDateFormat
import java.util.*
fun main() = runBlocking {
println("The third example related to the kotlin coroutine")
GlobalScope.launch {
println("The global scope is started")
delay(24L)
println("The scope task is finished")
}
println("STill it continues the main program task")
runBlocking {
delay(20L)
println("main program task is finished")
}
val a = async { example1() }
val b = async { example2() }
duration("The example 1 is executed waiting")
val out = a.await() + b.await()
duration("The out is $out")
}
suspend fun example1(): Int {
delay(12L)
duration("example1 is completed")
return 54
}
suspend fun example2(): Int {
delay(34L)
duration("example2 is completed")
return 6
}
fun duration(str: String) {
val z = (SimpleDateFormat("mm:hh:ss")).format(Date())
println("[$z] $str")
}
Output:
In the final example, we used time duration with the coroutine threads.
Conclusion
In kotlin language, a coroutine is implemented using asynchronous and non-blocking code. Basically, it’s implemented using the suspending functions at the language, and the coroutine scopes and builders are used to define the coroutines. The exceptions are treated as uncaught exceptions, and it is handled printed instead to the console.
Recommended Articles
This is a guide to Kotlin Coroutines. Here we discuss the introduction, syntax, and working of coroutines in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –