top of page

Do you know the tricky part of DisposableEffect in Jetpack Compose? 🤔




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? 👇

19 views0 comments

Comments


bottom of page