https://kotlinlang.org logo
Title
s

Saiedmomen

04/27/2022, 7:35 PM
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.
@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

tad

04/27/2022, 7:40 PM
The equivalent is
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

Saiedmomen

04/27/2022, 7:42 PM
yes but then you have the unused
onDispose
block
t

tad

04/27/2022, 7:42 PM
Yes, in practice it doesn't matter.
s

Saiedmomen

04/27/2022, 7:43 PM
you could have passed no args if you want it to run with every composition
t

tad

04/27/2022, 7:44 PM
It's trivial to write a wrapper:
@Composable
inline fun OneShotEffect(key: Any, noinline block: () -> Unit) {
    DisposableEffect(key) {
        block()
        onDispose { }
    }
}
👍 1
s

Saiedmomen

04/27/2022, 7:49 PM
yeah that seems nice. But why isn't it in the API? I keep thinking there should be a deeper reason for it :)
t

tad

04/27/2022, 7:50 PM
Probably to discourage side-effects 🙂
s

Saiedmomen

04/27/2022, 7:51 PM
Maybe extra suspending is super cheap?
t

tad

04/27/2022, 7:53 PM
LaunchedEffect
schedules its block on the main dispatcher, so its changes will always be reflected at least one frame later
👍 1
s

Saiedmomen

04/27/2022, 7:55 PM
I don't see very use cases for the
SideEffect
at all. You almost never want an effect to repeat on each composition
t

tad

04/27/2022, 7:56 PM
It's useful when you want to update a
remembered
state object through function parameters
👍 1
s

Saiedmomen

04/27/2022, 7:58 PM
why not just use
remeber(arg) {}
?
t

tad

04/27/2022, 7:59 PM
that would recreate the object when
arg
changes
s

Saiedmomen

04/27/2022, 8:01 PM
Can you please give a short snippet of how that would work?
never mind. I got it 👍
s

Saiedmomen

04/30/2022, 6:21 PM
@Rick Regan thanks! @Adam Powell Please consider mentioning the expected idempotency in the docs.