Colton Idle
09/05/2021, 8:01 PMval loggedIn: Flow<Boolean> = prefs.data
.map { preferences ->
preferences[authenticated] ?: false
}
This is my first time working with Flow, so I might be misunderstanding it's usage, but my use case is that when my app starts, I'm reading from prefs
and I need to know (at the moment the app starts) whether I'm logged in or logged out, but then every time after the first time, I want it to be async. Is there some typical pattern for when you want a flow... BUT you want to have the actual first item in the Flow before you go any further?Joffrey
09/05/2021, 9:38 PMStateFlow
could be an option here. Suspend until you get the initial value and create your StateFlow
with the initial value, then launch a coroutine to update the StateFLow
Colton Idle
09/05/2021, 9:57 PM.stateIn()
onto my code above, but the two issues I have with that is
1. I need a scope... but this should be a singleton so I guess I would just use GlobalScope?
2. When I add stateIn I get this error Suspend function 'stateIn' should be called only from a coroutine or another suspend function
Joffrey
09/05/2021, 10:41 PMGlobalScope
would be OK to use. However, should this really be in a singleton? Isn't there any sort of lifecycle you would like this to be tied to? It seems to me that the consumers of this state could actually be the ones providing the scope on the fly (after all, do you really need to listen to preference changes when no one is here to do anything with the value?).Joffrey
09/05/2021, 10:42 PMrunBlocking
Colton Idle
09/06/2021, 12:52 AMval loggedIn: StateFlow<Boolean> =
runBlocking {
prefs.data
.map { preferences ->
preferences[isAuthenticated] ?: false
}.stateIn(MainScope())
}
and to collect
vm.loggedInState.collectAsState()
but I seem to just be blocked? i.e. my app just hangs on launch on the splash screen lolJoffrey
09/06/2021, 1:03 AMrunBlocking
you need to be very careful which thread you're blocking. Using this during app initialization likely blocks the main thread. I don't know how the initial preferences are supposed to be fetched (haven't done Android stuff in a long time) but if this happens on the main thread too you might be creating a deadlock hereColton Idle
09/06/2021, 1:58 AMuli
09/06/2021, 5:02 AMuli
09/06/2021, 5:03 AMOrhan Tozan
09/06/2021, 11:33 AMColton Idle
09/08/2021, 2:44 AMColton Idle
09/08/2021, 2:44 AM