Understanding Side -effects in Jetpack Compose
I was trying to develop my Android app in Jetpack Compose. An important topic that influenced my Android app is “Side effects”. Side effects help us manage the state changes on the app’s UI.
Let us understand this with an example. In my app, “Mizu”, I wanted to show greetings on my home screen. The greetings could be like Good Evening, Good Morning and Good Night. They will depend on the user’s time. The ViewModel has the logic of greetings shown on the UI. I wanted to launch a one-off event (show greetings) on the home screen.
So, can we launch this event once from the UI without pressing a button or any user interaction?
The answer is using “side effect” APIs.
Why do we need side effects?
As I have previously explained in many of my blogs and videos, the composable functions should be “side effect” free. The composables can be executed in any order or due to unpredictable recomposition. We need to trigger the events in a controlled environment.
One example of the Side effect of APIs is the Launched- effect.
Launched-effect
The launched effect launches suspending functions inside of the composable UI. It launches a coroutine scope on recomposition that triggers events on the UI. If the recomposition happens or the launched effect restarts, the existing coroutine scope will exit, and a new coroutine scope will launch.
Let’s take a look at our example. In the case of “Mizu”, the greetings callback launches on the initialisation of the home screen. Therefore, the callback is inside of the Launched effect after delays.
Restarting Launched effect
The launched effect restarts with the help of keys. The keys could be the state changes in the app. For example, the state changes in an API call change from Loading to Success or Loading to Failure. These state changes can be used as Keys in Launched effects to trigger events in the UI.
I hope this makes the Side effects more clear. We will explore the rest in upcoming blogs. Thank you for reading.
If I have written something wrong, please forgive me. I hope you enjoyed reading.
Thank you,
Your Captain (the commute)
Hitesh Kohli.