Search code examples
kotlincoroutinekotlinx.coroutines

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.


Solution

  • 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
      }