diff --git a/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt b/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt index cbc9b2f2c..8fab59f2f 100644 --- a/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt +++ b/mirai-core/src/commonMain/kotlin/net.mamoe.mirai/utils/SuspendLazy.kt @@ -2,16 +2,18 @@ package net.mamoe.mirai.utils -import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import net.mamoe.mirai.contact.QQ +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.EmptyCoroutineContext /** - * 创建一个在当前 [CoroutineScope] 下执行的 [SuspendLazy] + * 创建一个在当前 [CoroutineScope] 下执行初始化的 [SuspendLazy] */ -fun CoroutineScope.SuspendLazy(initializer: suspend () -> R): Lazy> = SuspendLazy(this, initializer) +fun CoroutineScope.SuspendLazy(context: CoroutineContext = EmptyCoroutineContext, initializer: suspend () -> R): Lazy> = + SuspendLazy(this, context, initializer) /** * 挂起初始化的 [lazy], 是属性不能 `suspend` 的替代品. @@ -27,20 +29,12 @@ fun CoroutineScope.SuspendLazy(initializer: suspend () -> R): Lazy(scope: CoroutineScope, initializer: suspend () -> R) : Lazy> { - private val valueUpdater: Deferred by lazy { scope.async { initializer() } } +internal class SuspendLazy(scope: CoroutineScope, coroutineContext: CoroutineContext = EmptyCoroutineContext, initializer: suspend () -> R) : + Lazy> { + private val valueUpdater: Deferred by lazy { scope.async(context = coroutineContext) { initializer() } } - @Suppress("EXPERIMENTAL_API_USAGE") override val value: Deferred - get() = if (isInitialized()) { - CompletableDeferred(valueUpdater.getCompleted()) - } else { - CompletableDeferred().apply { - valueUpdater.invokeOnCompletion { - this.complete(valueUpdater.getCompleted()) - } - } - } + get() = valueUpdater override fun isInitialized(): Boolean = valueUpdater.isCompleted } \ No newline at end of file