https://kotlinlang.org logo
#compose
Title
# compose
a

Aaron Waller

05/09/2022, 1:56 PM
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

Rafael Costa

05/09/2022, 1:58 PM
You can have login state on a repository class that multiple view models listen to 🙂
🤝 1
3
c

Colton Idle

05/10/2022, 2:32 AM
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

Aaron Waller

05/10/2022, 7:14 PM
@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

Colton Idle

05/11/2022, 12:44 AM
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

Aaron Waller

05/12/2022, 11:08 AM
@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

Rafael Costa

05/12/2022, 11:10 AM
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

Aaron Waller

05/12/2022, 6:19 PM
@Rafael Costa Thank you so much! Just implemented it like you said and its working perfectly.
🙌 1
2 Views