I’m building my app in Jetpack Compose and use one...
# compose
a
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?
r
You can have login state on a repository class that multiple view models listen to 🙂
🤝 1
3
c
Yeah. Was basically going to say that you need your login state to live in your App scope and so basically you can create a singleton via Dagger if you use that, or just have this login state in your App class.
a
@Colton Idle Thank you. How should the user class look like? I never injected anything with hilt except of Room, Retrofit and Repositories 😬 Do I use a Data class for that? Or maybe a sealed class? This is what data I need to access from the user at all places in the app:
Copy code
data class UserState(
    val username: String = "",
    val isLoggedIn: Boolean = false,
    val isPremiumUser: Boolean = false,
    val coins: Int = 0
)
c
It can really look however you want it to look like (eg whatever fields you need), but yeah. It took me a long time to realize that for my entire Application, it's fine to have a "CurrentUser" that is available from everywhere.
a
@Colton Idle How do I observe this UserState object to see every change everywhere in the app? If you could check out my StackOverflow question I would be really happy, no one answered yet: https://stackoverflow.com/questions/72213441/access-the-login-state-from-every-screen-jetpack-compose-mvvm-hilt
r
You can use a StateFlow in the Repository
then all interested parties can collect on it
(remember to expose it as an immutable StateFlow)
btw in my personal opinion (but this also depends on your specific case), it doesn’t really make sense to have a “isLoggedIn” boolean. If the user is not logged in, don’t you want to clear all that state?
if so, I would just use a StateFlow<UserState?> (notice the “?”)
if user is loggedIn it won’t be null
if he’s logged out, its null
a
@Rafael Costa Thank you so much! Just implemented it like you said and its working perfectly.
🙌 1