How to access the Login state from everywhere? Jetpack Compose + MVVM

Viewed 264

I'm building my app in Jetpack Compose and use one ViewModel for every feature/screen. Now I need to access the login state from everywhere inside the app, I also have a coin system where I need access to from every screen.

How do I accomplish this? My first idea was to put the login state and coin state inside a "MainViewModel" and then use this in every Screen for example in my "SettingsScreen" composable use "SettingsViewModel" and "MainViewModel". But I'm not sure if this is a good practice to use two viewModels in one screen.

How can I have access to the Login state and the Coins in every screen?

1 Answers

You can use the singleton pattern to access your login credentials as either a global object or (better) a dependency that you inject into ViewModels which require that login state dependency. If you're using Dagger the @Singleton annotation is helpful

You could create a base ViewModel that injects that login state object into any class that inherits it.

If you're using the single activity pattern, you could scope your MainViewModel to that Activity and then access ViewModel from any fragment that is also scoped to that same Activity. This would be my preferred approach.

Related