https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Reuben

10/07/2023, 2:15 PM
Hey, I'm new to android development, so this might be a dumb question. I am trying to implement a simple login UI. I have some confusion between stateflow and suspend functions. I understand that if the UI needs to be constantly updated based on some sort of data lake that is constantly being updated, then stateflow is the way to go. However since the authentication request is just a 1 time HTTP call to a 3rd party endpoint, Im not sure which is better (saves more resources) stateflow or suspend. General overview: Android UI -> ViewModel -> Repository Repository will make a HTTP request to authenticate the user. For the UI, I'm using composables and have a state variable (possibly stored in local storage to tell if a user is authenticated). Since this is a 1 time network request (only when the user logs in), do I need a stateflow? or will suspend functions be enough. Some reason as to your suggestion may help me understand better! Thanks!
s

s3rius

10/07/2023, 2:59 PM
The authentication request would be best as a suspend function. As you said it returns a result (success or failure) just once at the end of its run, so suspend fits the bill. Where you might want to have a StateFlow is for that state variable you mentioned. StateFlow is basically a variable that you can subscribe to to be notified when it changes. So you run your authentication function and update the value of your StateFlow when it finishes. If you want to know if you're authenticated you go to your StateFlow. If you want to know if the authentication request was successful, you look at the result of that suspend call (e.g. to show an error message to your user).
🙏 1
p

Patrick Steiger

10/07/2023, 10:46 PM
Events up, state down. The request to authenticate can be a suspend function This call should end up updating the state (possibly stored in StateFlow). Activity subscribes to state and shows corresponding UI.
🙏 1
At least this is the architecture recommended by Google. You might decide to do something completely different and that’s fine
r

Reuben

10/08/2023, 12:16 AM
Ahhh, these makes alot of sense and is helping me understand when to use what better!! Thank you so much!
u

uli

10/08/2023, 8:22 PM
Do you need to show activity (e.g. a spinner) while the request is being processed by your authentication backend? Then a state flow might still be right. You can then do the following: 1. Initialize with
mutableStateFlow(Idle)
2. When login is requested,
emit(Loading)
3. When successful
emit(Success)
or
emit(Success(token))
depending on your needs 4. When not successful
emit(Error(exception))
Idle
,
Loading
,
Success
and
Error
can be modelled as sealed classes.