Handling Side Effects - devrath/ComposeAlchemy GitHub Wiki
Jetpack Compose is a modern toolkit for creating beautiful UI components. It uses a declarative approach for building the UI. It works by composing the UI once and re-composing it repeatedly again and again. Important things to note here is managing the state of the composable here
A state can be considered a value in a UI component.
Example can be a text that is considered for a counter composable, The value of the text can be considered as a state.
The composable observes the state and updates the composable based on the value updated on the state.
The state and event flow is unidirectional.
What is a Side-Effect?
Anything that escapes the scope of the function where it is called that would result in unpredictable re-compositions is called a state.
Sometimes We require a state, to handle some scenarios like the below under certain conditions
Showing a snack bar
Navigating to a different screen
So the side effect is called in a controlled environment that is aware of the life cycle of composable.
Also the side effects such as Updating the DB, and making the network call` must be kept outside separately from the UI rendering logic to ensure the maintainability of the code.
The compose library provides several effects to manage the side effects, by decoupling from the UI logic and executing a coroutine scope.
Benefits of using Side-Effect?
Separating the non-UI-related operation from UI-related operation, By doing so code remains responsive, and easier to understand and maintain.
One of the applications involves logging the analytics operations which could help developers debug applications in a better way
The use of SideEffect is beneficial when you need to perform actions that are not directly related to the UI rendering but are tied to the state changes in your composable.
Use cases of side effects are
Handling animation.
Interacting with external systems.
Performing One-Time Initialization such as setting up a connection to a Bluetooth device
SideEffect in Jetpack compose is a function call which is not a composable functionbutinside a composable function.
No side-effect
There is Side-effect
Another example of a side effect
@Composable
funNumberGuessDemoScreen() {
normalFunction() // --> This is also a side effect Column(
verticalArrangement =Arrangement.Center,
horizontalAlignment =Alignment.CenterHorizontally
) {
}
}
If side effects occur in a compose, There are effect handlers to handle these effects. So they are called effect handlers.