Skip to content

Instantly share code, notes, and snippets.

@Laimiux
Last active September 23, 2019 23:10
Show Gist options
  • Save Laimiux/265c350c988cbd09d7a4757987f3a15e to your computer and use it in GitHub Desktop.
Save Laimiux/265c350c988cbd09d7a4757987f3a15e to your computer and use it in GitHub Desktop.
class StopwatchFormula : Formula<Unit, StopwatchState, StopwatchRenderModel> {
override fun initialState(input: Unit) = StopwatchState(
timePassedInMillis = 0,
isRunning = false
)
override fun evaluate(
input: Unit,
state: StopwatchState,
context: FormulaContext<StopwatchState>
): Evaluation<StopwatchRenderModel> {
return Evaluation(
renderModel = StopwatchRenderModel(
timePassed = formatTimePassed(state.timePassedInMillis),
startStopButton = startStopButton(state, context),
resetButton = resetButton(state, context)
)
)
}
private fun formatTimePassed(timePassedInMillis: Long): String {
// TODO: actually format it.
return "$timePassedInMillis ms"
}
private fun startStopButton(state: StopwatchState, context: FormulaContext<StopwatchState>): ButtonRenderModel {
return ButtonRenderModel(
text = if (state.isRunning) "Stop" else "Start",
onSelected = context.callback {
transition(state.copy(isRunning = !state.isRunning))
}
)
}
private fun resetButton(state: StopwatchState, context: FormulaContext<StopwatchState>): ButtonRenderModel {
return ButtonRenderModel(
text = "Reset",
onSelected = context.callback {
transition(state.copy(timePassedInMillis = 0, isRunning = false))
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment