Skip to content

Instantly share code, notes, and snippets.

@shafty023
Created June 10, 2020 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shafty023/7b87501435851c450564ab9a985e944d to your computer and use it in GitHub Desktop.
Save shafty023/7b87501435851c450564ab9a985e944d to your computer and use it in GitHub Desktop.
StateMachine
/**
* Keeps track of current and prior application state.
*
* @param dataStore storage
*/
@Singleton
class StateMachine(private val dataStore: DataStore) {
/**
* Storage implementation for our state machine.
*
* @param currentState the current state of the application
* @param lastKnownError the last error that occurred
* @param lastActionPerformed the last action the user performed
*/
@DataStore.Key(key = "StateMachine")
private data class StateStorage(
var currentState: Int,
var lastKnownError: String?,
var lastActionPerformed: String?
)
// Restore our storage from DataStore or create a new instance if one hasn't been created
private val stateStorage: StateStorage = dataStore.restore(StateStorage::class.java,
GsonUtils::deserialize) ?: StateStorage(0, null, null)
private fun saveChanges() {
// Call this any time a change is made to a variable within StateStorage
dataStore.save(stateStorage, GsonUtils::serialize)
}
// Add methods to access/update data in stateStorage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment