Trending October 2023 # How Coroutines Works In Kotlin With Examples # Suggested November 2023 # Top 17 Popular | Nhunghuounewzealand.com

Trending October 2023 # How Coroutines Works In Kotlin With Examples # Suggested November 2023 # Top 17 Popular

You are reading the article How Coroutines Works In Kotlin With Examples updated in October 2023 on the website Nhunghuounewzealand.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested November 2023 How Coroutines Works In Kotlin With Examples

Introduction to Kotlin Coroutines

Web development, programming languages, Software testing & others

Syntax:

import kotlinx.coroutines.* fun main() = runBlocking { launch{ delay(values) }

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 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") } 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") 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 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:

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 –

You're reading How Coroutines Works In Kotlin With Examples

Update the detailed information about How Coroutines Works In Kotlin With Examples on the Nhunghuounewzealand.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!