Skip to content

Instantly share code, notes, and snippets.

@pfn
Created February 12, 2016 03:22
Show Gist options
  • Save pfn/0f3025725efc7f05579d to your computer and use it in GitHub Desktop.
Save pfn/0f3025725efc7f05579d to your computer and use it in GitHub Desktop.
naive attempt at a state machine
import android.app.Activity
import android.os.Bundle
import ActivityStateMachine._
/**
* @author pfnguyen
*/
trait ActivityStateMachine[T <: State[T]] extends Activity {
private[this] var state: T = _
override def onDestroy() = {
super.onDestroy()
state = state.transition(state.state, DESTROYED)
}
override def onCreate(savedInstanceState: Bundle) = {
super.onCreate(savedInstanceState)
state = state.transition(state.state, CREATED)
}
override def onStop() = {
super.onStop()
state = state.transition(state.state, STOPPED)
}
override def onStart() = {
super.onStart()
state = state.transition(state.state, STARTED)
}
override def onResume() = {
super.onResume()
state = state.transition(state.state, RESUMED)
}
override def onPause() = {
super.onPause()
state = state.transition(state.state, PAUSED)
}
}
object ActivityStateMachine {
sealed trait LifecycleState
case object DESTROYED extends LifecycleState
case object STOPPED extends LifecycleState
case object PAUSED extends LifecycleState
case object RESUMED extends LifecycleState
case object STARTED extends LifecycleState
case object CREATED extends LifecycleState
trait State[T <: State[T]] {
def state: LifecycleState
def transition(prev: LifecycleState, next: LifecycleState): T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment