Coroutines job returning a value

Viewed 1676

I'm trying to do something like this with Kotlin Coroutines (this is pseudocode):

suspend fun myFunction() {
  if (job.isActive) {
    job.join()
    return job.result
  } else {
    job.start()
    job.join()
    return job.result
  }
}

Basically, to have a job that executes some code and returns a value. Then the function uses that job. If the job is not started, it executes it and returns its results. If the job is already started, it waits till its finished and returns its result.

But not sure how to approach this. Any suggestion?

2 Answers
class MyClass(override val coroutineContext: CoroutineContext) : CoroutineScope {
    private val lazyThing =
        async(start = CoroutineStart.LAZY) {
            5 // Calculate using suspending functions as necessary
        }

    suspend fun getThing() = lazyThing.await()
}

lazyThing ends up being a Deferred<Int>. Its contents won't be calculated until the first time getThing() is called. It will only be calculated once, after which its value will be returned immediately.

import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext


fun main() {
    println(myFunction())
}

fun myFunction(): Int = runBlocking {
    aJobAsync().await()
}

suspend fun aJobAsync(): Deferred<Int> = withContext(Dispatchers.Default) {// use Dispatchers.IO for IO intensive task
    async {
        2 + 2
    }
}

aJobAsync - this will return the deferred, which can used to retrieve the jobs return value

myFunction - is a runBlocking block, which mean when calling myFunction the caller thread will be blocked. Since we need coroutine scope to call a await on a job

Related