Architecture is quite a difficult thing to wrap your head around. Today I’m going to show you a simple way to get your app running with some of the benefits of highly complex architectures but keeping it low code count, readable and allows you to keep structure, iterate and build fast. So first let’s start with the state.
The state of the page basically holds all the information of what the user would see and the state of the page, whether it’s loading or not, what action is currently being displayed on the screen, etc. It manages all the UI elements on the screen
The viewModelState below has two parts, the ViewModel state which holds all the information an enum State which I’ll explain later. From the code you can see that the ViewModelState just holds whether the page is loading or not, a list of items and what state the app is already in (START or COMPLETE)
Next we’ll move to the viewMode. This is where all the network and database work are done and lives outside of the activity/fragment lifecycle
In the ViewModel below you can see that we have a variable state, error and api. The viewModel handles and manages the state of the screen, setting it loading or not and setting the items in a request and setting the state of the screen which you can see in the init block
And finally we get to the activity/fragment. The fragment creates an instance of the fragment and does network calls through the viewModel which then updates the state and the results get pushed back upwards.
From the Fragment below you can see that all I’m doing is instantiating the viewModel, listening on the state and error and changing the UI(setting the progress bar visible and gone). The if statement should definitely be a when statement where you can switch on and off functionality or navigate back based on the state. Important to remember is to never change the value of the state inside of handleViewState as this would just create a cyclical call.
I hope that by reading this, you don’t get overwhelmed by architecture and use or create something tailored more to your style and needs. You do not need to follow an architecture but take only the parts you need and add your own if you need to.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
3rd Party Cookies
This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.
Keeping this cookie enabled helps us to improve our website.
Please enable Strictly Necessary Cookies first so that we can save your preferences!