Created
April 2, 2026 14:17
-
-
Save guiathayde/20949b9eb03e4047f6bf255f9caf80df to your computer and use it in GitHub Desktop.
Corotinas em Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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