Commit e251631d authored by Leonardo Aramaki's avatar Leonardo Aramaki

Implement ConnectionStatusManager class including a implementation of a FSM to...

Implement ConnectionStatusManager class including a implementation of a FSM to handle connection states
parent 57089ec4
package chat.rocket.android
import chat.rocket.android.service.KeepAliveJob
import unquietcode.tools.esm.EnumStateMachine
import unquietcode.tools.esm.TransitionException
object ConnectionStatusManager {
enum class State {
OFFLINE, CONNECTING, ONLINE
}
private const val DEBUG = false
private val stateMachine: EnumStateMachine<State>
init {
stateMachine = EnumStateMachine(State.OFFLINE)
stateMachine.addTransitions(State.OFFLINE, State.CONNECTING)
stateMachine.addTransitions(State.CONNECTING, State.ONLINE, State.OFFLINE)
stateMachine.addTransitions(State.ONLINE, State.OFFLINE)
}
@Synchronized
fun currentState() = stateMachine.currentState()
@Synchronized
fun setOnline(callback: TransitionCallback) {
KeepAliveJob.cancelPendingJobRequests()
tryTransitionTo(State.ONLINE, callback)
}
@Synchronized
fun setConnecting(callback: TransitionCallback) {
KeepAliveJob.cancelPendingJobRequests()
tryTransitionTo(State.CONNECTING, callback)
}
@Synchronized
fun setConnectionError(callback: TransitionCallback) {
KeepAliveJob.schedule()
tryTransitionTo(State.OFFLINE, callback)
}
private fun tryTransitionTo(newState: State, callback: TransitionCallback) {
try {
stateMachine.transition(newState)
callback.onTransitioned(true)
} catch (e: TransitionException) {
if (DEBUG) {
e.printStackTrace()
}
callback.onTransitioned(false)
}
}
interface TransitionCallback {
fun onTransitioned(success: Boolean)
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment