Kotlin Coroutines

 

Coroutines are lightweight threads.By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.



Coroutines are basically of two types:

  • Stackless
  • Stackful
Stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t map on the native thread.

Kotlin Coroutines Features.


Lightweight-One can run many coroutines on a single thread due to support for suspension, which doesn’t block the thread where the coroutine is running. Suspending frees memory over blocking while supporting multiple concurrent operations.
Built-in cancellation support:Cancellation is generated automatically through the running coroutine hierarchy.
Fewer memory leaks: It uses structured concurrency to run operations within a scope.
Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that one can use for structured concurrency.


Kotlin Coroutines Dependencies

Add these dependencies in build.gradle app-level file.

dependencies 
{
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x"
}



Coroutine Basics: Launch, Async and RunBlocking.

Launch

launch is used to fire and forget coroutine. It's perfect for cases where you don't need to compute any result. Here's a simple example:


import kotlinx.coroutines.*

fun main() {
GlobalScope.launch {
delay(1000L)
println("Hello from Coroutine!")
}
println("Hello from Main Thread!")
Thread.sleep(2000L)
}


In this code, we’re launching a new coroutine using GlobalScope.launch. Inside this coroutine, we're delaying for one second (1000 milliseconds), and then printing a message.


Async

async is used when you need a result computed in a coroutine. It starts a new coroutine and returns a Deferred<T>, which is a non-blocking future that represents a promise to provide a result later. Here's an 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
}


In this code, we’re launching a new coroutine and starting a computation inside it using async. This computation is a suspend function computeResult, which delays for one second and then returns the number 42. After the computation, we print the result using await.


RunBlocking

runBlocking is a bridge between non-coroutine world and coroutine world. It's a way to start top-level main coroutine. Here's how to use it:


import kotlinx.coroutines.*

fun main() = runBlocking {
launch {
delay(1000L)
println("Hello from Coroutine!")
}
println("Hello from Main Thread!")
}


In this code, we’re starting a main coroutine using runBlocking, and inside this coroutine, we're launching a new coroutine.


Coroutine Context and Dispatchers

Every coroutine in Kotlin has a context associated with it, which is a set of various elements. The key elements in this set are Job of the coroutine and its dispatcher.


Dispatchers

In simple words, coroutine dispatchers determine what thread or threads the corresponding coroutine uses for its execution. Kotlin provides three main dispatchers:

  • Dispatchers.Main — for UI-related tasks.
  • Dispatchers.IO — for input/output tasks, like reading or writing from/to a database, making network calls, or reading/writing files.
  • Dispatchers.Default — for CPU-intensive tasks, like sorting large lists or doing complex computations.





import kotlinx.coroutines.*

fun main() = runBlocking {
launch(Dispatchers.IO) {
println("IO: ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) {
println("Default: ${Thread.currentThread().name}")
}
launch(Dispatchers.Main) {
println("Main: ${Thread.currentThread().name}")
}
}







Popular posts from this blog

Simple Sign up design. Android.

Cart page design in android.

Set Date on jDateChooser and retrieve record from database.