Do you know the tricky part of DisposableEffect in Jetpack Compose? š¤
- Nikolay Miroshnychenko

- Dec 25, 2023
- 1 min read
This is a partial answer to the challenge š§© I posted three days ago
Jetpack Compose has introduced āside effectsā for handling various Android-specific scenarios.
Such side effects include LaunchedEffect, DisposableEffect, rememberCoroutineScope, and others.
The example in the challenge was probably not the best usage of DisposableEffect - because, as one of my LinkedIn followers has mentioned - this couldāve been solved with rememberCoroutineScope.
RememberCoroutineScope() cancels š the scope when the enclosing Composable leaves the Composition.
The best usage for DisposableEffect is whenever you need to perform an actual āclean-up.ā This usually refers to listener removal.
For example, you might have a GPS sensor whose events you listen to in the UI. In such a case, you should put all your clean-up logic in the onDispose part of DisposableEffect.
Another thing that you should remember about DisposableEffect is that it acts similarly to LaunchedEffect. Both have keys š that they track. Both recompose when that key š changes.
In our example, we had a DisposableEffect with a Unit for its key. While such an approach might have a use case for one-off events - it wasnāt appropriate in our example. We wanted to show a new UserProfile when userId changes.
Iāve tried to put the whole explanation in the video š„.
What do you think of the previous challenge? Was it too much code?
Also, Iām thinking of doing the explanations with examples on YouTube or in longer-form articles - as I will be able to make them faster than the video below. What do you guys think? š






Comments