Join in Kotlin coroutines

 In Kotlin coroutines, the join() function is used to wait for the completion of multiple coroutines running concurrently. It allows you to ensure that all the launched coroutines finish their execution before proceeding further in the code.

When you launch multiple coroutines using launchasync, or other coroutine builders, you obtain references to these launched coroutines. You can store these references in variables and later use join() on each of these variables to wait for the corresponding coroutines to complete.


import kotlinx.coroutines.*

suspend fun doTaskA() {
println(“Task A started”)
delay(2000) // Simulate some asynchronous work for 2 seconds
println(“Task A finished”)
}

suspend fun doTaskB() {
println(“Task B started”)
delay(3000) // Simulate some asynchronous work for 3 seconds
println(“Task B finished”)
}

fun main() = runBlocking {
val jobA = launch { doTaskA() }
val jobB = launch { doTaskB() }

println(“Launched both coroutines, now waiting for them to complete…”)

// Wait for both coroutines to complete using join()
jobA.join()
jobB.join()

println(“Both coroutines have completed.”)
}


Output

Task A started
Task B started
Task A finished
Task B finished
Both coroutines have completed.

Popular posts from this blog

Simple Sign up design. Android.

Cart page design in android.

Set Date on jDateChooser and retrieve record from database.