Photo by James Wheeler from Pexels

Login / Logout Flow: Android Jetpack Compose and CompositionLocal

Paul Allies
2 min readNov 5, 2021

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.

  1. When the user is successfully logged in (isLoggedIn = true), they are directed to the rest of the application views.
  2. When a user is logged out (isLoggedIn = false) at any point within the app, they are directed to the login page.
Flow

We need the following components:

  1. User State View Model
  2. Application Switcher
  3. Login Screen
  4. 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

Application Switcher

Login Screen

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:

--

--