Created
January 10, 2020 17:45
-
-
Save oliveira-marcio/497a6a53fea852c2d9938c4a9c87a479 to your computer and use it in GitHub Desktop.
State Machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class StateMachine<T, E>( | |
private val dispatcher: Dispatcher, | |
private val errorFactory: ErrorFactory<E>, | |
protected var currentState: State<T, E> = State(State.Name.IDLE), | |
private val listeners: MutableList<StateListener<T, E>> = mutableListOf() | |
) { | |
abstract fun start() | |
fun addStateChangedListener(listener: StateListener<T, E>) { | |
this.listeners.add(listener) | |
listener.onStateChanged(currentState) | |
} | |
fun removeStateChangedListener(listener: StateListener<T, E>) { | |
this.listeners.remove(listener) | |
} | |
fun loadNewState(function: () -> T) { | |
if (currentState.name == State.Name.LOADING) { | |
changeAndEmitState(currentState) | |
return | |
} | |
changeAndEmitState( | |
State( | |
State.Name.LOADING, | |
currentState.value | |
) | |
) | |
dispatcher.dispatch( | |
{ | |
changeAndEmitState( | |
State( | |
State.Name.LOADED, | |
function.invoke() | |
) | |
) | |
}, | |
{ throwable -> | |
changeAndEmitState( | |
State( | |
State.Name.ERROR, | |
currentState.value, | |
errorFactory.create(throwable) | |
) | |
) | |
} | |
) | |
} | |
private fun changeAndEmitState(state: State<T, E>) { | |
currentState = state | |
for (listener in listeners) { | |
listener.onStateChanged(currentState) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment