Soy nuevo en kotlin y su concepto coroutine.
Tengo debajo de la rutina usando withTimeoutOrNull -
import kotlinx.coroutines.* fun main() = runBlocking { val result = withTimeoutOrNull(1300L) { repeat(1) { i -> println("I'm with id $i sleeping for 500 ms ...") delay(500L) } "Done" // will get cancelled before it produces this result } println("Result is $result") }Producción -
I'm sleeping 0 ... Result is DoneTengo otro programa coroutine sin tiempo de espera -
import kotlinx.coroutines.* fun main() = runBlocking { val result = launch { repeat(1) { i -> println("I'm sleeping $i ...") delay(500L) } "Done" // will get cancelled before it produces this result } result.join() println("result of coroutine is ${result}") }producción -
I'm sleeping 0 ... result of coroutine is StandaloneCoroutine{Completed}@61e717c2¿Cómo puedo obtener el resultado del cálculo en kotlin coroutine cuando no uso withTimeoutOrNull como mi segundo programa?
launch no devuelve nada, por lo que debe:
Use async y await (en cuyo caso, await devuelve el valor)
import kotlinx.coroutines.* fun main() = runBlocking { val asyncResult = async { repeat(1) { i -> println("I'm sleeping $i ...") delay(500L) } "Done" // will get cancelled before it produces this result } val result = asyncResult.await() println("result of coroutine is ${result}") }No use el lanzamiento en absoluto ni mueva su código que está dentro del lanzamiento a una función de suspensión y use el resultado de esa función:
import kotlinx.coroutines.* fun main() = runBlocking { val result = done() println("result of coroutine is ${result}") } suspend fun done(): String { repeat(1) { i -> println("I'm sleeping $i ...") delay(500L) } return "Done" // will get cancelled before it produces this result }