Skip to content

Instantly share code, notes, and snippets.

@guiathayde
Created April 2, 2026 14:17
Show Gist options
  • Select an option

  • Save guiathayde/20949b9eb03e4047f6bf255f9caf80df to your computer and use it in GitHub Desktop.

Select an option

Save guiathayde/20949b9eb03e4047f6bf255f9caf80df to your computer and use it in GitHub Desktop.
Corotinas em Kotlin
package com.guiathayde.lib
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.random.Random
import kotlin.time.Duration.Companion.seconds
fun randomSeconds(): Int {
return Random.nextInt(5, 15)
}
suspend fun callWebAPI1(): String {
println("Start call to API 1 ...")
val myDelay = randomSeconds()
delay(myDelay.seconds)
return "Data 1 returned in $myDelay seconds."
}
suspend fun callWebAPI2(): String {
println("Start call to API 2 ...")
val myDelay = randomSeconds()
delay(myDelay.seconds)
return "Data 2 returned in $myDelay seconds."
}
fun main() = runBlocking {
launch {
val deferredA: Deferred<String> = async(Dispatchers.IO) {
callWebAPI1()
}
val deferredB: Deferred<String> = async(Dispatchers.IO) {
callWebAPI2()
}
val res = listOf(deferredA, deferredB).awaitAll()
println(res)
}
println("End of runBlocking")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment