Skip to content

Instantly share code, notes, and snippets.

@iKunalChhabra
Created June 4, 2024 12:15
Show Gist options
  • Save iKunalChhabra/3d7f85852479b1752ca8d56e9244ef31 to your computer and use it in GitHub Desktop.
Save iKunalChhabra/3d7f85852479b1752ca8d56e9244ef31 to your computer and use it in GitHub Desktop.
kotlin_coroutines.kt
package com.kunalchhabra
import kotlinx.coroutines.*
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
// Launch a new coroutine in background and continue
val result1 = async { fetchDataFromSource1() }
val result2 = async { fetchDataFromSource2() }
// Wait for all the coroutines to complete and get the results
val combinedResult = result1.await() + result2.await()
val endTime = System.currentTimeMillis()
println("Combined Result: $combinedResult")
println("Time taken: ${endTime - startTime} ms")
}
suspend fun fetchDataFromSource1(): Int {
delay(1000L) // Simulate a long-running task
println("Fetched data from source 1")
return 10
}
suspend fun fetchDataFromSource2(): Int {
delay(1500L) // Simulate a long-running task
println("Fetched data from source 2")
return 20
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment