docs/counter.md
Getting started with Mavericks is simple. Once it is integrated into your project, let's walk through a simple counter example. We're going to make this:
When you click the counter text, the count goes up by one. Code for this sample can be found here.
The first step in creating a Mavericks screen is to model it as a function of state. Modeling a screen as a function of state is a useful concept because it is:
A counter screen is simple to model.
data class CounterState(val count: Int = 0) : MavericksState
val) property, count, it is an integer, and it defaults to 0.MavericksState signals the intention that this class will be used as Mavericks state.Next, we need to create a ViewModel which will own CounterState and be responsible for updating it.
class CounterViewModel(initialState: CounterState) : MavericksViewModel<CounterState>(initialState) {
fun incrementCount() {
setState { copy(count = count + 1) }
}
}
CounterState.() -> CounterState . The receiver of the reducer is the current state when the reducer is run and it returns the updated state. copy is the kotlin data class copy function.First, we need to create the layout. It is simply a TextView that will display the count in the middle of the screen.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/counterText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="48dp" />
</FrameLayout>
Then, we need to create our Fragment.
class CounterFragment : Fragment(R.layout.counter_fragment), MavericksView {
private val viewModel: CounterViewModel by fragmentViewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
counterText.setOnClickListener {
viewModel.incrementCount()
}
}
override fun invalidate() = withState(viewModel) { state ->
counterText.text = "${state.count}"
}
}
viewModel.incrementCount(). Calling named functions on your ViewModel is like the intent from the MVI world.invalidate() from MavericksView. invalidate() will be called any time the state for any view model retrieved with a view model delegate changes.withState(viewModel) to access the current state of our ViewModel at the time invalidate() was called.state.count to the TextView's text.Congratulations, you have built your first Mavericks screen!