Is there a reason for the vanilla `SideEffect` not...
# compose
s
Is there a reason for the vanilla
SideEffect
not having key args? In the example in the official docs, you can see that there easily can be extra calls to the analytics. The
LaunchedEffect
is great but the suspend block is sometimes not needed and wasteful.
Copy code
@Composable
fun rememberAnalytics(user: User): FirebaseAnalytics {
    val analytics: FirebaseAnalytics = remember {
        /* ... */
    }

    // On every successful composition, update FirebaseAnalytics with
    // the userType from the current User, ensuring that future analytics
    // events have this metadata attached
    SideEffect {
        analytics.setUserProperty("userType", user.userType)
    }
    return analytics
}
t
The equivalent is
Copy code
DisposableEffect(key) {
    ...
    onDispose { }
}
I assume
SideEffect
with a
key
doesn't make much sense to implement as its purpose is to run on every composition.
s
yes but then you have the unused
onDispose
block
t
Yes, in practice it doesn't matter.
s
you could have passed no args if you want it to run with every composition
t
It's trivial to write a wrapper:
Copy code
@Composable
inline fun OneShotEffect(key: Any, noinline block: () -> Unit) {
    DisposableEffect(key) {
        block()
        onDispose { }
    }
}
👍 1
s
yeah that seems nice. But why isn't it in the API? I keep thinking there should be a deeper reason for it :)
t
Probably to discourage side-effects 🙂
s
Maybe extra suspending is super cheap?
t
LaunchedEffect
schedules its block on the main dispatcher, so its changes will always be reflected at least one frame later
👍 1
s
I don't see very use cases for the
SideEffect
at all. You almost never want an effect to repeat on each composition
t
It's useful when you want to update a
remembered
state object through function parameters
👍 1
s
why not just use
remeber(arg) {}
?
t
that would recreate the object when
arg
changes
s
Can you please give a short snippet of how that would work?
never mind. I got it 👍
s
@Rick Regan thanks! @Adam Powell Please consider mentioning the expected idempotency in the docs.