https://kotlinlang.org logo
Title
m

Marcin Wisniowski

05/01/2023, 9:20 PM
I've been seeing a pattern of using
DisposableEffect
with an empty
onDispose {}
. What is the reasoning behind it? One example is here: https://google.github.io/accompanist/systemuicontroller/#usage
o

orangy

05/01/2023, 9:29 PM
If it were called
CompositionEffect
and the callback called
onDecompose
it could be more clear, that it’s a “lifecycle” thing rather than necessarily the disposable thing.
a

Alex Vanyo

05/01/2023, 9:36 PM
It’s generally an anti-pattern, hopefully you aren’t seeing it in too many places. The system bars is an exceptional case where the window flags (an external piece of state) are being kept in sync with some Compose state It’s extra weird since the window flags don’t have any way to observe changes, so there’s nothing to “clean up” either (which might go in a
onDispose
block). Window flags are a really awkward API to work with from the perspective of Compose.
m

mattinger

05/02/2023, 3:01 AM
That does seem kind of odd. I suppose one could use LaunchedEffect in that case, but that spawns a coroutine, so there's more overhead. I get the feeling you could pretty easily put some syntactic sugar around it and call it "ComposedEffect" or something like that. Or if you're really ambitious you can look at the source and basically duplicate what they did for DisposableEffect and treat it a bit different to have the cleanup code block be optional
l

Loney Chou

05/02/2023, 3:20 AM
Effects other than
SideEffect
are built upon
RememberObserver
, which can be invalidated by
key
parameter, so the block will only be executed when something has changed. I'd suggest having another
SideEffect
which is also built this way, so no empty
onDispose
workaround any more. Anyway, it's more of a semantic issue.