Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin coroutines get results from launch

I'm new to kotlin and its concept coroutine.

I have below coroutine using 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")
    }

Output -

    I'm sleeping 0 ...
    Result is Done

I have another coroutine program without timeout -

    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}")
    }

output -

    I'm sleeping 0 ...
    result of coroutine is StandaloneCoroutine{Completed}@61e717c2

How can I get the result of computation in kotlin coroutine when I don't use withTimeoutOrNull like my second program.

like image 802
Rajkumar Natarajan Avatar asked Feb 01 '19 19:02

Rajkumar Natarajan


1 Answers

launch does not return anything, so you have to either:

  1. Use async and await (in which case, await does return the value)

    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}")
    }
    
  2. Not use launch at all or move your code that is inside the launch into a suspending function and use the result of that function:

    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
    }
    
like image 143
Adib Faramarzi Avatar answered Sep 29 '22 14:09

Adib Faramarzi