as we know the `SideEffect` gets triggered on ever...
# compose
m
as we know the
SideEffect
gets triggered on every recomposition so it works fine in the code below(triggered only once when
MainScreen
starts composition), but if I uncomment the
LaunchedEffect
the
SideEffect
block will get triggered whenever the
count
state changes, while if I comment the
LaunchedEffect
block it will not. why?
a
Because of the
count
access when calling
LaunchedEffect
m
yes
LaunchedEffect
has access but
SideEffect
doesn't, how does
LaunchedEffect
affect
SideEffect
?
a
It doesn't. If you split out your parameters into temporary variables and expand the property delegation you can see what's happening:
Copy code
val count = remember { mutableStateOf(0) }

SideEffect { ... }

val currentCount = count.value // accessing count's value invalidates MainScreen

LaunchedEffect(currentCount) { ... }
MainScreen
is reading
count
and listening for invalidations of it in order to obtain the value to pass as the
LaunchedEffect
key
👍 1
But if you comment out the line of code that contains the
count
read, then
MainScreen
no longer invalidates when
count
changes. It has no reason to.
👍 1
z
If you place LaunchedEffect inside the Scaffold, the SideEffect wouldnt run again would it?
👍 1
a
It shouldn't, but inline composables share an invalidation scope with their caller, so you'll see no difference with things like
Box
. You can't just count the
{}
nesting 🙂
👍🏼 1
👍 1
👍🏽 1
If you have to think about this sort of thing this hard to make your code behave correctly, you're probably relying too much on side effects in general. This can be useful to know when analyzing performance, but it should never affect correctness
👍 3
c
@Adam Powell I'm being a bit pedantic here because I'm also really trying to learn sideEffects but the OP says "as we know the 
SideEffect
 gets triggered on every recomposition" is that true or is it better/more accurate to say "gets triggered at the end of every successful recomposition"?
s
Definitely being pedantic yeah 😅 This detail can be omitted in the context of what is being discussed here imo
a
if you want to dial pedantry to 11... "The
SideEffect
function executes on every recomposition of the recompose scope it appears in, scheduling the provided function parameter to execute after the changes from the composition are successfully applied and
RememberObservers
have run"
💯 1
🤷‍♂️ 1
🤯 2
😬 1