diff --git a/elmslie-core/src/main/kotlin/money/vivid/elmslie/core/store/Actor.kt b/elmslie-core/src/main/kotlin/money/vivid/elmslie/core/store/Actor.kt index b36a7957..62db5663 100644 --- a/elmslie-core/src/main/kotlin/money/vivid/elmslie/core/store/Actor.kt +++ b/elmslie-core/src/main/kotlin/money/vivid/elmslie/core/store/Actor.kt @@ -2,6 +2,7 @@ package money.vivid.elmslie.core.store import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.sync.Mutex @@ -11,7 +12,7 @@ import kotlin.reflect.KClass abstract class Actor { - protected val switchers = mutableMapOf, Switcher>() + private val switchers = mutableMapOf, Switcher>() private val mutex = Mutex() /** @@ -26,16 +27,20 @@ abstract class Actor { ) = mapNotNull { eventMapper(it) } .catch { errorMapper(it)?.let { event -> emit(event) } ?: throw it } - protected fun Flow.switchOnEach(command: Command, delayMillis: Long = 0): Flow { + protected fun Flow.asSwitchFlow(command: Command, delayMillis: Long = 0): Flow { return flow { val switcher = mutex.withLock { switchers.getOrPut(command::class) { Switcher() } } - switcher.switch(delayMillis) { this@switchOnEach }.collect { + switcher.switch(delayMillis) { this@asSwitchFlow }.collect { emit(it) } } } + + protected fun cancelSwitchFlow(command: KClass): Flow { + return switchers[command]?.cancel() ?: emptyFlow() + } } diff --git a/samples/coroutines-loader/src/main/kotlin/money/vivid/elmslie/samples/coroutines/timer/elm/TimerActor.kt b/samples/coroutines-loader/src/main/kotlin/money/vivid/elmslie/samples/coroutines/timer/elm/TimerActor.kt index fbb4ce12..440b6021 100644 --- a/samples/coroutines-loader/src/main/kotlin/money/vivid/elmslie/samples/coroutines/timer/elm/TimerActor.kt +++ b/samples/coroutines-loader/src/main/kotlin/money/vivid/elmslie/samples/coroutines/timer/elm/TimerActor.kt @@ -4,24 +4,19 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import money.vivid.elmslie.core.store.Actor -import money.vivid.elmslie.core.switcher.Switcher internal object TimerActor : Actor() { - private val switcher = Switcher() - override fun execute(command: Command) = when (command) { is Command.Start -> secondsFlow() - .switchOnEach(command) + .asSwitchFlow(command) .mapEvents( eventMapper = { Event.OnTimeTick }, errorMapper = { Event.OnTimeError(it) }, ) - is Command.Stop -> switchers.getOrPut(Command.Start::class) { - Switcher() - }.cancel() + is Command.Stop -> cancelSwitchFlow(Command.Start::class) } @Suppress("MagicNumber")