From a1d8d744d01470fb57cd700e08ef95922702f6f7 Mon Sep 17 00:00:00 2001 From: Him188 <Him188@mamoe.net> Date: Sun, 16 Apr 2023 10:28:09 +0100 Subject: [PATCH] [core] CoroutineOnDemandValueScope: fix emit when state is ProducerReady --- .../auth/CoroutineOnDemandValueScope.kt | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt b/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt index 0365060a7..5a068a772 100644 --- a/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt +++ b/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt @@ -73,6 +73,10 @@ internal class CoroutineOnDemandValueScope<T, V>( } } + is ProducerState.ProducerReady -> { + setStateProducing(state) + } + else -> throw IllegalProducerStateException(state) } } @@ -96,6 +100,14 @@ internal class CoroutineOnDemandValueScope<T, V>( } } + private fun setStateProducing(state: ProducerState.ProducerReady<T, V>) { + val deferred = CompletableDeferred<V>(coroutineScope.coroutineContext.job) + if (!compareAndSetState(state, ProducerState.Producing(state.producer, deferred))) { + deferred.cancel() // avoid leak + } + // loop again + } + private fun finishImpl(exception: Throwable?) { state.loop { state -> when (state) { @@ -173,11 +185,7 @@ internal class CoroutineOnDemandValueScope<T, V>( } is ProducerState.ProducerReady -> { - val deferred = CompletableDeferred<V>(coroutineScope.coroutineContext.job) - if (!compareAndSetState(state, ProducerState.Producing(state.producer, deferred))) { - deferred.cancel() // avoid leak - } - // loop again + setStateProducing(state) } is ProducerState.Producing -> return true // ok @@ -201,4 +209,4 @@ internal class CoroutineOnDemandValueScope<T, V>( override fun finish() { finishImpl(null) } -} +} \ No newline at end of file