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

Mjahangiry75

02/18/2022, 2:26 PM
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

Alexander Maryanovsky

02/18/2022, 2:38 PM
Because of the
count
access when calling
LaunchedEffect
m

Mjahangiry75

02/18/2022, 2:42 PM
yes
LaunchedEffect
has access but
SideEffect
doesn't, how does
LaunchedEffect
affect
SideEffect
?
a

Adam Powell

02/18/2022, 2:58 PM
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

Zoltan Demant

02/18/2022, 2:59 PM
If you place LaunchedEffect inside the Scaffold, the SideEffect wouldnt run again would it?
👍 1
a

Adam Powell

02/18/2022, 3:00 PM
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

Colton Idle

02/18/2022, 5:07 PM
@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

Stylianos Gakis

02/18/2022, 6:08 PM
Definitely being pedantic yeah 😅 This detail can be omitted in the context of what is being discussed here imo
a

Adam Powell

02/18/2022, 6:17 PM
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
3 Views