https://kotlinlang.org logo
Title
b

Berkeli Alashov

07/13/2022, 7:21 PM
I'm trying to understand the difference in LaunchedEffect and SideEffect in example below.
@Composable
fun isCompactWindow(windowSizeClass: WindowSizeClass = LocalWindowSizeClass.current) = windowSizeClass.isCompactWindow()

class Fragment : ComposeFragment { // calls Route in onCreateView by returning ComposeView

    @Composable
    override fun Route() {
        val isCompactWindow = isCompactWindow()
        val someOtherState by remember { mutableStateOf(false) }

        LaunchedEffect(isCompactWindow){
            mainActivity.showFoo(isCompactWindow)
        }
        // or
        SideEffect {
            mainActivity.showFoo(isCompactWindow)
        }
    }
}
I think I should use the LaunchedEffect in this case. Since it makes sure that the code won't run again when
someOtherState
changes, right? If there was only
isCompactWindow
, then I could use SideEffect safely too?
s

Stylianos Gakis

07/13/2022, 8:52 PM
SideEffect will run on every recomposition, meaning that you should expect mainActivity.showFoo to be run multiple times, hundreds even if you got for example an animation running that makes this scope recompose. If it does only run once in your case consider it something that you should not rely on. LaunchedEffect will run once and then every time isCompactWindow changes.
:thank-you: 1