At upday, we’ve been successfully using the Model-View-ViewModel pattern together with RxJava for more than a year and a half. After sharing with the community a very high-level overview of what this pattern entails, we decided that it’s time to go deeper into the implementation details.
I will present our way of handling Android classes and other 3rd party dependencies, and how we make sure that our code is as unit-testable as possible. I’ll speak about our decision process on how to split classes, may they be Views, ViewModels or DataModels, and the benefits and drawbacks of these separations.
Any non-”Hello World” app will most likely have two things: multiple Activities/Fragments, of which at least one will contain a ListView/RecyclerView. Then I’ll show how we handle lists: how is the data added to the list, and how and who listens and reacts to list items taps.
60. public class TopNewsStreamView extends Fragment {
@Inject
TopNewsStreamViewModel viewModel;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
…
onInject();
}
61. public class TopNewsStreamView extends Fragment {
@Inject
TopNewsStreamViewModel viewModel;
@Override
public void onResume() {
…
bind();
}
@Override
public void onPause() {
…
unbind();
}
62. Lifecycle of the ViewModel depends on the lifecycle of the View
Only the View has a reference to the corresponding ViewModel
Only other native android classes know about the View
78. public class TopNewsAdapter extends
RecyclerView.Adapter<TopNewsViewHolder> {
@Override
public TopNewsViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
// create a view holder with a new view
// that represents items of the given type
}
83. public class TopNewsAdapter extends
RecyclerView.Adapter<TopNewsViewHolder> {
@Override
public TopNewsViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
// create a view holder with a new view
// that represents items of the given type
// create the view model
}
84. ViewModel creates and emits the Model for the View
View subscribes to the emissions of the Model
View updates the RecyclerView.Adapter
The View and the corresponding ViewModel are created in
Adapter.onCreateViewHolder
100. Define an Action in the View’s Model
Bind the Model to the View via the RecyclerView.ViewHolder
Trigger the Action
Action is handled by the ViewModel
101. It’s All In The
Implementation
Details
@FMuntenescu
upday
MVVM
https://goo.gl/bIwdmc