Marcello Galhardo
12/16/2021, 9:09 PMSideEffect
it says:
To share Compose state with objects not managed by compose, use theIf acomposable, as it’s invoked on every successful recomposition.SideEffect
SideEffect
is called on “each recomposition”, what is the difference between the two codes:
@Composable
fun sample(user: User) {
// 1. With Side Effect, called each successful recomposition.
SideEffect { analytics.setUserProperty("userType", user.userType) }
// 2. No SideEffect, called each recomposition.
analytics.setUserProperty("userType", user.userType)
}
My understand is that a SideEffect
would not be triggered if a recomposition happens (similar to LaunchedEffect
and how it works with the keys) but based in the docs I think I’m missing something…Casey Brooks
12/16/2021, 9:26 PMSideEffect
function is it's called on every successful recomposition. So if there's an exception or something else that might interfere with the recomposition, the SideEffect
doesn't get called, helping to avoid leaving your application in a bad state.Marcello Galhardo
12/16/2021, 9:33 PMCasey Brooks
12/16/2021, 9:42 PMMarcello Galhardo
12/16/2021, 9:56 PMDisposableEffect(viewModel) {
// do something
onDispose { }
}
It would be really nice if SideEffect
would support keys too so I don’t need to use onDispose
empty for these cases. 😞Sean McQuillan [G]
12/16/2021, 10:09 PMMarcello Galhardo
12/16/2021, 10:13 PMZach Klippenstein (he/him) [MOD]
12/16/2021, 10:14 PM@Composable fun Thing() {
SideEffect {
doThingSafely()
}
doThingUnsafely()
throw RuntimeException("oopsie")
}
doThingSafely
would never get called, but doThingUnsafely
would, even though the composition would never be applied, none of its UI would actually get emitted, and no state changes it performed would take effect.JulianK
12/17/2021, 9:08 AMyschimke
12/17/2021, 11:41 AM