Kotlin Coroutines with Examples

In the simplest terms, a coroutine is a way to write asynchronous code sequentially. It is a lightweight thread used in applications. Coroutines are defined as "lightweight threads" by the Kotlin team. They are the types of jobs that actual threads can complete. 

Coroutines were added to Kotlin in version 1.3 and are based on well-known notions from other languages. Kotlin coroutines are a new type of concurrency that may be utilized on Android to simplify async mobile applications.

There are three types of coroutines
  • Launch
  • Async
  • RunBlocking
 1. Launch: Launch is used to fire and forget coroutine, Here’s a simple example

 import kotlinx.coroutines.*

 fun main() {

GlobalScope.launch {

delay(1000L)

println("Hello Coroutine!")

}

println("Hello Main Thread!")

Thread.sleep(2000L)

 }

We are launching a new coroutine using Goblaescope.launch inside of coroutine . delay is one second then print message. 

2. Asyn: It is part of coroutines . it starts a new coroutine and returns a Deferred<T > .which is a non-blocking future .Here’s example

import kotlinx.coroutines.*

fun main() {

GlobalScope.launch {

val result = async {

computeResult()

}

println("Computed result: ${result.await()}")

}

Thread.sleep(2000L)

}

suspend fun computeResult(): Int {

delay(1000L)

 Return 42

}

This computation is suspend function computerResult which delays for one second then return 42.

​3.RunBlocking: RunBlocking is a bridge between the coroutine world and the coroutine world. It is a way to start the top main coroutine.

 import kotlinx.coroutines.*

 fun main() = runBlocking {

launch {

delay(1000L)

println("Hello from Coroutine!")

}

println("Hello from Main Thread!")

 }


Happy coding! 













  

 

365Bloggy May 16, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive