Login / Logout Flow: Android Jetpack Compose and CompositionLocal
CompositionLocal is useful when you want to create a dependency in a higher node of the layout tree and use it on a lower node without having to pass it down the tree through every child Composable.
Here we will use it to direct our application when a user logs in and out.
- When the user is successfully logged in (isLoggedIn = true), they are directed to the rest of the application views.
- When a user is logged out (isLoggedIn = false) at any point within the app, they are directed to the login page.
We need the following components:
- User State View Model
- Application Switcher
- Login Screen
- Home Screen
User State View Model
The user state view model keeps track of and broadcasts our user status. We are going to store this view model to a CompositionLocal.
We make our view model instance available to all child composables, starting from the ApplicationSwitcher composable
The Login screen can now use the UserStateViewModel to invoke signIn
Home Screen with Logout Button
The Home screen also uses the UserStateViewModel to invoke the signOut
At all times the Application Switcher is monitoring the isLoggedIn status: