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

ritesh

03/03/2022, 8:59 PM
Why
SideEffect
gets called ever-time my composable is
invalidated
, but same does-not hold true for
LaunchedEffect
? Query in 🧵
1
🧵 1
d

dewildte

03/04/2022, 4:19 AM
By design perhaps?
r

ritesh

03/04/2022, 7:53 AM
Aren't effect handlers tied to composable life cycle? Probably i am missing something, in this scenario
a

Alexander Maryanovsky

03/04/2022, 8:19 AM
That’s what
LaunchedEffect
does - it’s only executed once (every time the value of its key changes).
SideEffect
is executed on every recomposition.
r

ritesh

03/04/2022, 8:52 AM
Yes, I understand the difference
SideEffect
-> on every successful composition and re-composition, if it's part of it
LaunchedEffect
-> when its enters composition and span across re-composition unless the keys are changed.
But in above scenario - this code particularly
Copy code
@Composable
fun MyTopLevelComposable(viewModel:MyViewModel){

  when (val state = viewModel.response.observeAsState().value) { // observing live-data state
    is Content -> LaunchedEffect(Unit) { launchActivity() }
    Error -> SideEffect { someDialog.value = true}
  }
}
It will never get recomposed. The only reason for this composable to be called again could be if compose compiler invalidates the view. My Query is -> when view/composable gets
invalidated
SideEffect {someDialog.value = true}
executes, because it will again go through
composition
not
re-composition
as
viewModel.response(which is live-data)
last state was
Error
But if change it to
LaunchedEffect(Unit) {someDialog.value = true}
it doesn't executes again after the composable is invalidated. It only reacts to a new state emitted by the live-data. Question is why?
Invalidate
should start composition again, and since it's a composition. not re-composition
LaunchedEffect
should behave similarly to
SideEffect
in this scenario, as both are reaching to composition. Or May be i am missing something here?
6 Views