
jvmMain.com.toxicbakery.kfinstatemachine.RxStateMachine.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kfin-jvmRx Show documentation
Show all versions of kfin-jvmRx Show documentation
Kotlin library for creating finite state machines.
The newest version!
package com.toxicbakery.kfinstatemachine
import com.toxicbakery.kfinstatemachine.TransitionEvent.EnterTransition
import com.toxicbakery.kfinstatemachine.TransitionEvent.ExitTransition
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
/**
* An observable that reports transition events before and after they are applied to the machine.
*/
val StateMachine.stateObservable: Observable>
get() = Observable.create { emitter ->
val rxCallback = RxStateCallback(emitter)
registerCallback(rxCallback)
emitter.setCancellable { unregisterCallback(rxCallback) }
}
val StateMachine.enterTransitionObservable: Observable>
get() = stateObservable
.filter { event -> event is EnterTransition }
.map { event -> event as EnterTransition }
val StateMachine.exitTransitionObservable: Observable>
get() = stateObservable
.filter { event -> event is ExitTransition }
.map { event -> event as ExitTransition }
sealed class TransitionEvent {
/**
* Event signal when a transition is in progress.
*
* @param currentState the current state of the machine
* @param transition the transition that initiated the state change
* @param targetState the resulting state of this transition
*/
data class EnterTransition(
val stateMachine: StateMachine,
val currentState: S,
val transition: T,
val targetState: S
) : TransitionEvent()
/**
* Event signal when a transition has completed.
*
* @param previousState the previous state of the machine before the transition was applied
* @param transition the transition that initiated the state change
* @param currentState the resulting state of this transition
*/
data class ExitTransition(
val stateMachine: StateMachine,
val previousState: S,
val transition: T,
val currentState: S
) : TransitionEvent()
}
/**
* Captures machine state changes and reports them to the observable.
*
* @param emitter of the observable to report to
*/
private class RxStateCallback(
private val emitter: ObservableEmitter>
) : TransitionCallback {
override fun enteringState(
stateMachine: StateMachine,
currentState: S,
transition: T,
targetState: S
) = emitter.onNext(EnterTransition(stateMachine, currentState, transition, targetState))
override fun enteredState(
stateMachine: StateMachine,
previousState: S,
transition: T,
currentState: S
) = emitter.onNext(ExitTransition(stateMachine, previousState, transition, currentState))
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy