From 76bfeb44c5a02be143c152c52bc1029cff360744 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Sat, 21 Mar 2020 22:04:31 +0100 Subject: refactor: Migrate to Flow for event listeners --- .../kotlin/com/atlarge/odcsim/flow/StateFlow.kt | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) (limited to 'odcsim/odcsim-api/src/main/kotlin') diff --git a/odcsim/odcsim-api/src/main/kotlin/com/atlarge/odcsim/flow/StateFlow.kt b/odcsim/odcsim-api/src/main/kotlin/com/atlarge/odcsim/flow/StateFlow.kt index 429d932b..0410bd95 100644 --- a/odcsim/odcsim-api/src/main/kotlin/com/atlarge/odcsim/flow/StateFlow.kt +++ b/odcsim/odcsim-api/src/main/kotlin/com/atlarge/odcsim/flow/StateFlow.kt @@ -28,7 +28,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.channels.BroadcastChannel -import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.ConflatedBroadcastChannel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.FlowCollector import kotlinx.coroutines.flow.asFlow @@ -58,31 +58,22 @@ public fun StateFlow(value: T): StateFlow = StateFlowImpl(value) /** * Internal implementation of the [StateFlow] interface. */ +@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) private class StateFlowImpl(initialValue: T) : StateFlow { /** * The [BroadcastChannel] to back this flow. */ - @OptIn(ExperimentalCoroutinesApi::class) - private val chan = BroadcastChannel(Channel.CONFLATED) + private val chan = ConflatedBroadcastChannel(initialValue) /** * The internal [Flow] backing this flow. */ - @OptIn(FlowPreview::class) private val flow = chan.asFlow() - init { - @OptIn(ExperimentalCoroutinesApi::class) - chan.offer(initialValue) - } - - @OptIn(ExperimentalCoroutinesApi::class) - public override var value: T = initialValue + public override var value: T + get() = chan.value set(value) { - if (field != value) { - chan.offer(value) - field = value - } + chan.offer(value) } @InternalCoroutinesApi -- cgit v1.2.3