协程任务返回值

3

我想用 Kotlin 协程实现以下功能(这是伪代码):

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

简单来说,就是有一个能执行一些代码并返回一个值的任务。然后函数使用这个任务。如果该任务尚未启动,则它会执行它并返回其结果。如果该任务已经启动,则函数等待任务完成并返回其结果。

但不确定如何处理这个问题。有什么建议吗?

2个回答

0
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 最终会成为一个 Deferred<Int>。它的内容直到第一次调用 getThing() 才会被计算。它只会被计算一次,之后它的值将立即返回。


0
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
    }
}
- 这将返回延迟对象,可以用于检索作业的返回值。 - 是一个 runBlocking 块,这意味着在调用 myFunction 时,调用线程将被阻塞。由于我们需要协程范围来调用作业的 await。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接