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

martinsumera

03/09/2021, 3:30 PM
I’m looking at SideEffect explanation on the https://developer.android.com/jetpack/compose/lifecycle but I don’t really understand why and when should I use it. Can somebody explain me what is the difference between the following:
Copy code
val backCallback = remember { /* ... */ }
SideEffect {
    backCallback.isEnabled = enabled
}

and

val backCallback = remember { /* ... */ }
backCallback.isEnabled = enabled
a

Adam Powell

03/09/2021, 3:33 PM
The latter performs a side effect during composition, which you should avoid.
backCallback
is not a Compose-aware object and should not be mutated during composition. The
SideEffect
API is a way to defer these kinds of side effects until the composition has successfully been applied, and side effects are executed on the main thread, whereas composition may happen on other threads.
If composition fails or is never applied, it's as if that composition never happened. Compose can "roll back" (or simply not commit) changes made to snapshot state (e.g.
mutableStateOf
objects) but it's generally much harder to do this for objects that weren't written to work with Compose
so an easy solution to this is to use
SideEffect
to defer the operation until the composition is applied instead, when there's no potential need to roll back/discard the composition pass anymore.
👍 3
m

martinsumera

03/09/2021, 3:42 PM
Thanks for the explanation, it’s clear to me now 👍
👍 1
4 Views