Last active
January 11, 2019 03:33
-
-
Save itome/6b22e43cebbb00743bd83cf77c470a25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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