Authenticating your user is one of the most common tasks that we encounter as Android developers. And while there are various ways to authenticate, ranging from Firebase authentication up to a dedicated API, It's always an advantage to follow the best practices of clean architecture to ensure a modular and robust application. The final goal is a flow in which the user enjoys a seamless high quality experience.
In this article, I'll be showing how I followed the MVVM architectural pattern to implement a clean Login/Registration flow. In which I used the following components:
- Kotlin Flows
- ViewModels
- UiState classes
I should be mentioning early on that this article tackles a the high-level concepts and doesn't dive deep into implementation details or explains what different architectural components are.
Now let the fun begin:
Result Class
Our first task is creating a Result class to wrap the network requests. By utilizing Kotlin
's sealed classes and generics, we can create a clean network wrapper with a few lines of code:
Models
To encapsulate our logic, we create a User
class to abstract our authenticated user, For now, it's kept so simple to hold the basic user details.
Repository
Next comes the design of our data layer. We extract the authentication methods into an interface, which makes the code loosely coupled and assists with future implementation swaps as well as testing. For sake of simplicity, the methods only expose the state of the request in Boolean
.
To learn more about callbackFlow
see this
ViewModels and UiState
After we have successfully setup our repositories, it's time create our `ViewModels. We're going to expose only one field of UiState class which encapsulates our UI logic to adhere to Android's Unidirectional Data Flow
We bind the LoginViewModel
to the LoginFragment
. The Logic will be as follow:
If User is signed in, navigate to
HomeFragment
.Else, navigate user to
RegistrationFragment
.
LoginUiState
LoginViewModel
LoginViewFragment
Final notes
Thank you very much for your precious time! I write about #AndroidDev, #FlutterDev, and #CleanArchitecture
You can reach me at ahmed.g.obied@gmail.com
You can also visit my personal blog at Ahmed Gadein
Cheers! ✨