Jetpack Compose Side Effects — DisposableEffect: effects that require cleanup

Hello Folks,
I, hope you are doing great and composing beautiful android apps. Why won’t you when google and android bodies have put great effort into writing the amazing jetpack compose toolkit for UI for us?
This article is going to be about one very important topic of the Side-Effects API of JPC (Jetpack Compose) DisposableEffect.
If you haven’t read my other articles on side effect API, I’ll highly recommend you guys to check out my article for Sideffect and LaunchEffect from the Sideeffect API.
From official docmentation
For side effects that need to be cleaned up after the keys change or if the composable leaves the Composition, use DisposableEffect
Why it’s important?
For example, When you acquire resources and now you want to get it clean when your view is no more available, you are supposed to release that resource and will help GC to clean up any dangling pointer ;).
There is another use-case for understanding this API, for example, you want to let your server know when you entered Screen 1 and how much time you stayed there.
Enough is Enough
Enough words, let’s have an example, as usual, to explore this API in detail I am making a demo for my fellow readers.
In this example, I am making a console demo where I will mock a screen time tracking process in the minimum possible way.
Here you can see I am calling startLogging() method from my viewmodel when I enter into my TimerScreen composable function, and on next few lines you can see the onDispose method that will be called when TimerScreen method will be disposed of, hence I can do my wrap up/ clean up or finish my stuff if required. In the above example, I am trying to user screen with on given Composable.
For more detail, I’ve attached GitHub source code as well so feel free to checkout, compile and run examples to fully understand this problem.
In the next article, I’ll explain one more interesting topic from sideeffect series “rememberUpdatedState”, If you like this article, please clap and subscribe for more exciting stuff.
Bye Bye
Share this article

Written by : admin
Latest Articles
June 21, 2024
June 11, 2024
June 10, 2024
May 31, 2024
May 27, 2024
May 10, 2024
February 1, 2024
December 28, 2023
December 26, 2023
December 18, 2023
December 15, 2023
September 26, 2023
September 21, 2023
September 19, 2023
September 19, 2023
September 12, 2023
September 5, 2023
August 29, 2023
March 31, 2023
March 20, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023
March 13, 2023