so I have this block of code ```lifecycleScope.la...
# coroutines
o
so I have this block of code
Copy code
lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { uiState ->
            if (uiState.authenticated) {
                setContent {
                    Home()
                }
            } else {
                setContent {
                    Authentication()
                }
            }
        }
    }
}
and the issue is that it’s collecting the stateFlow immediately before my viewModel gets the chance return the result, so it shows Authentication, then when the value comes back ti shows Home again I want it to…well observe like LiveData does
and i really don’t get what on earth
distinctUntilChanged
is trying to do with its signature
I could solve it by setting authenticated to start off as null, looks like this
Copy code
if (uiState.authenticated != null) {
    if (uiState.authenticated) {
        setContent {
            Home()
        }
    } else {
        setContent {
            Authentication()
        }
    }
}
but is that really how to do it ?
nothing is working as long as
authenticated
has an initial value
i dont know whether this is even the way to do it, im kind of treating it like LiveData but it doesnt want to behave like livedata
a
I'm not quite sure which behavior of LiveData you're comparing against
o
well it doesnt grab initial value the moment i start observing and acts on it immediately
only when .postValue is called on the livedata does the observer trigger
a
oh the ambiguous initial state
o
yea authenticated will start as false
then viewmodel finishes, becomes true
it triggeres for both values
a
fwiw if we were designing it again today we'd probably make it work like StateFlow does instead, that behavior was kind of regrettable
your code will get clearer if you model the rest of your assumptions
o
so there’s something logically im not getting
a
authenticated
can't be a boolean because you're assuming that there's something special about, "not yet authenticated because I'm waiting on some sort of confirmation"
or rather, it can't only be a boolean. There's another piece of state not being modeled here. There's a third, "I'm not sure yet" state
o
Loading
success, and failure
ok i see
a
right. working in state is about modeling those assumptions as part of the state itself
o
i see
ok thats clearer
a
remove the elements of, "over time" from the system; the state unambiguously tells you everything you need to know
o
yea, that “while this is fetching that” is a state in itself
a
yep, exactly. if something is ambiguous, clarify it in the state
o
gotttt it
thanks!
👍 1
a
this is also why StateFlow and friends all
distinctUntilChanged
by default and "skip" intermediate values if an observer isn't responding fast enough: it should never matter to an observer so long as the state is being modeled fully. The latest, current state is all you ever need.
o
works 🙂
👍 1