1
0
mirror of https://github.com/mamoe/mirai.git synced 2025-04-25 13:03:35 +08:00

[core] CoroutineOnDemandValueScope: remove CreatingProducer state

This commit is contained in:
Him188 2023-04-22 12:02:04 +01:00
parent d263a9ee29
commit 10e731f260
2 changed files with 12 additions and 21 deletions
mirai-core/src/commonMain/kotlin/network/auth

View File

@ -175,12 +175,10 @@ internal class CoroutineOnDemandValueScope<T, V>(
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<T, V>(
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.

View File

@ -32,11 +32,6 @@ internal sealed interface ProducerState<T, V> {
* |
* | 调用 [expectMore]
* |
* V
* CreatingProducer
* |
* |
* |
* V
* ProducerReady (从此用户协程作为 producer 在后台运行)
* |
@ -105,17 +100,15 @@ internal sealed interface ProducerState<T, V> {
val producer: OnDemandProducerScope<T, V>
}
// This is need — to ensure [launchProducer] is called exactly once.
class CreatingProducer<T, V>(
launchProducer: () -> OnDemandProducerScope<T, V>
) : HasProducer<T, V> {
override val producer: OnDemandProducerScope<T, V> by lazy(launchProducer)
override fun toString(): String = "CreatingProducer"
}
class ProducerReady<T, V>(
override val producer: OnDemandProducerScope<T, V>,
launchProducer: () -> OnDemandProducerScope<T, V>,
) : HasProducer<T, V> {
override val producer: OnDemandProducerScope<T, V> by lazy(launchProducer) // `lazy` is synchronized
fun startProducerIfNotYet() {
producer
}
override fun toString(): String = "ProducerReady"
}