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

Jeisson Sáchica

12/05/2020, 5:21 PM
Is there a way to achieve a behavior similar to the SnapshotMutationPolicy of MutableState with onCommit (or basically remember)?
a

Adam Powell

12/05/2020, 5:33 PM
Can you describe the use case?
j

Jeisson Sáchica

12/05/2020, 5:46 PM
Basically I have a
MutableState<String>
on my MainActivity which I pass to one of my screen composables and I update its value like this
state.value = googleToken
after I get a token on onActivityResult from GoogleSignInActivity. Inside my login screen i have a onCommit block that I execute whenever this token changes.
Copy code
val googleIdToken by googleIdTokenState
onCommit(googleIdToken) {
    googleIdToken?.let { token ->
        loginViewModel.checkIfGoogleUserExists(token) {
            // If it exists, login and navigate "Home" immediately
            // If it does not exist, navigate to next screen "Register" for the user to input a username
        }
    }
}
My problem comes when for example, the user navigates to register screen and then navigates back and again clicks on the "Sign in with Google" button. on the onActivityResult I will get the same token but the MutableState won't change. I managed to make it change by creating it with a
neverEqualPolicy()
but of course the onCommit block won't execute again
Maybe what I need is not a MutableState but something like a flow, so that I can act on every change no matter what its value is 🤔
a

Adam Powell

12/05/2020, 6:54 PM
Yeah that's what I'd recommend. Whenever you find yourself using
onCommit
to dispatch change events to some other part of your system it's a bit of a code smell
💯 1
Part of why that form of
onCommit
is going away, replaced by
SideEffect
and
DisposableEffect
If you want to watch for changes to a snapshot state outside of composition you can use
snapshotFlow
j

Jeisson Sáchica

12/05/2020, 7:23 PM
Yeah you're definitely right. Thanks, I'll take a look into snapshotFlow
6 Views