presentation • Uses Observer pattern to notify changes ViewModel is... • Abstraction of the view exposing public properties and commands • State of the data in the model • Maintains the state of the view • Value converter (raw data to presentation-friendly properties)
Showing Dialogs, Toasts, Snackbars • Event listeners • Starting Activities • Handling Menu • Handling permissions • Other Android specific stuff & methods which require reference to the Activity Context
empty, error, etc.) • Exposing data • Handling visibility • Handling Extras & Arguments (Bundle) • Input validation • Executing data calls in the Model • Executing UI commands in the View
separate business logic from UI • Example - 3 screens, loading data on different actions ViewModel loadUsers() onRefreshButtonClick() onDialogPositiveClick() Activity #1 onRefreshButtonClick() Activity #3 viewModel.onGeolocationRespond() Activity #2 onDialogPositiveClick() SOLID
What is wrong: ❌ Mixing display logic with UI ❌ Breaking single responsibility (to show data) ❌ Impossible to unit test and hard to debug Better way: • Views should be as dumb as possible • Primitive expressions are probably OK
state = new ObservableField<>(); public final ObservableField<StockEntity> stock = new ObservableField<>(); private DataProvider mDataProvider; // represents model @Override public void onStart() { super.onStart(); if(stock.get() == null) loadStock(); } public void loadStock() { if(NetworkUtility. isOnline(StocksApplication. getContext())) { state.set(StatefulLayout.State. PROGRESS); mDataProvider.loadStock(...); // retrieves data from model and updates stock and state fields } else { state.set(StatefulLayout.State. OFFLINE); } } ... }