Android 中的 Kotlin 惰性协程

Aun*_*win 2 android android-architecture-components kotlin-coroutines

我正在尝试为我的协程创建惰性函数。我创建了这样的 util 函数。

fun <T> lazyCoroutine(scope: CoroutineScope, block: suspend CoroutineScope.() -> T): Lazy<T> {

    val some = scope.async(start = CoroutineStart.LAZY) {
        block.invoke(this)
    }
    return lazy {
        some.await()
    }
}
Run Code Online (Sandbox Code Playgroud)

但在终端显示

我的错误

我也不想回来Deferred<T>,我只想回来刚出来的deferred。我看到大部分文章返回的内容Deferred<T>与我的场景不符。有没有相关的解决办法请指点一下。祝你有美好的一天!。

我的情景

Mar*_*nik 6

我看到大部分文章返回的内容Deferred<T>与我的场景不符。

你还没有说清楚到底什么是不合适的Deferred,但如果它是await()一个可挂起的函数,那么你似乎要求自相矛盾的结果:你希望用户调用一个不可挂起的函数,但实现使用可挂起的实现,并且您期望总体结果是非阻塞的。无论进行多少包装或调整,都无法避免来自可挂起域外部的阻塞。

如果您想继续使用普通的、不可挂起的函数,那么根本不要使用协程,它们将只是另一层复杂性,并且您的线程仍然会阻塞,直到该值可用为止。

如果您可以使用可挂起的功能,那么您应该接受Deferred

fun <T> CoroutineScope.lazyCoroutine(
        block: suspend CoroutineScope.() -> T
): Deferred<T> {
    return async(start = CoroutineStart.LAZY) { block() }
}
Run Code Online (Sandbox Code Playgroud)