From 10e731f260e571c95f785e52c1538dd6078ff4b6 Mon Sep 17 00:00:00 2001 From: Him188 Date: Sat, 22 Apr 2023 12:02:04 +0100 Subject: [PATCH] [core] CoroutineOnDemandValueScope: remove CreatingProducer state --- .../auth/CoroutineOnDemandValueScope.kt | 12 +++++------ .../kotlin/network/auth/ProducerState.kt | 21 +++++++------------ 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt b/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt index 5a068a772..9fad94aeb 100644 --- a/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt +++ b/mirai-core/src/commonMain/kotlin/network/auth/CoroutineOnDemandValueScope.kt @@ -175,12 +175,10 @@ internal class CoroutineOnDemandValueScope( state.loop { state -> when (state) { is ProducerState.JustInitialized -> { - compareAndSetState(state, ProducerState.CreatingProducer { Producer(ticket) }) - // loop again - } - - is ProducerState.CreatingProducer -> { - compareAndSetState(state, ProducerState.ProducerReady(state.producer)) + val ready = ProducerState.ProducerReady { Producer(ticket) } + if (compareAndSetState(state, ready)) { + ready.startProducerIfNotYet() + } // loop again } @@ -193,7 +191,7 @@ internal class CoroutineOnDemandValueScope( is ProducerState.Consuming -> throw IllegalProducerStateException(state) // a value is already ready is ProducerState.Consumed -> { - if (compareAndSetState(state, ProducerState.ProducerReady(state.producer))) { + if (compareAndSetState(state, ProducerState.ProducerReady { state.producer })) { // wake up producer async. state.producerLatch.resumeWith(Result.success(ticket)) // loop again to switch state atomically to Producing. diff --git a/mirai-core/src/commonMain/kotlin/network/auth/ProducerState.kt b/mirai-core/src/commonMain/kotlin/network/auth/ProducerState.kt index 99666a2ed..128ac9ebe 100644 --- a/mirai-core/src/commonMain/kotlin/network/auth/ProducerState.kt +++ b/mirai-core/src/commonMain/kotlin/network/auth/ProducerState.kt @@ -32,11 +32,6 @@ internal sealed interface ProducerState { * | * | 调用 [expectMore] * | - * V - * CreatingProducer - * | - * | - * | * V * ProducerReady (从此用户协程作为 producer 在后台运行) * | @@ -105,17 +100,15 @@ internal sealed interface ProducerState { val producer: OnDemandProducerScope } - // This is need — to ensure [launchProducer] is called exactly once. - class CreatingProducer( - launchProducer: () -> OnDemandProducerScope - ) : HasProducer { - override val producer: OnDemandProducerScope by lazy(launchProducer) - override fun toString(): String = "CreatingProducer" - } - class ProducerReady( - override val producer: OnDemandProducerScope, + launchProducer: () -> OnDemandProducerScope, ) : HasProducer { + override val producer: OnDemandProducerScope by lazy(launchProducer) // `lazy` is synchronized + + fun startProducerIfNotYet() { + producer + } + override fun toString(): String = "ProducerReady" }