Skip to content

Instantly share code, notes, and snippets.

@itome
Last active January 11, 2019 03:33
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 itome/6b22e43cebbb00743bd83cf77c470a25 to your computer and use it in GitHub Desktop.
Save itome/6b22e43cebbb00743bd83cf77c470a25 to your computer and use it in GitHub Desktop.
sealed class CounterIntent : Intent {
object IncrementIntent : CounterIntent()
object DecrementIntent : CounterIntent()
}
sealed class CounterAction : Action {
data class UpdateCountAction(val count: Int) : CounterAction()
}
data class CounterState(val count: Int = 0) : State
class CounterViewModel : OwlViewModel<CounterIntent, CounterAction, CounterState>(initialState = CounterState()) {
override fun intentToAction(intent: CounterIntent, state: CounterState): CounterAction = when (intent) {
IncrementIntent -> UpdateCountAction(state.count + 1)
DecrementIntent -> UpdateCountAction(state.count - 1)
}
override fun reducer(state: CounterState, action: CounterAction): CounterState = when (action) {
is UpdateCountAction -> state.copy(count = action.count)
}
}
class MainActivity : AppCompatActivity() {
private val counterViewModel: CounterViewModel by lazy {
ViewModelProviders.of(this).get(CounterViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
...
buttonIncrement.setOnClickListener {
counterViewModel.dispatch(IncrementIntent)
}
buttonDecrement.setOnClickListener {
counterViewModel.dispatch(DecrementIntent)
}
counterViewModel.state.observe(this, Observer { state ->
textCount.text = "count: ${state.count}"
})
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment