Junior — Middle
How is the @Restartable annotation functionality implemented in Jetpack Compose and what is its purpose?
sobes.tech AI
Answer from AI
The @Restartable annotation in Jetpack Compose is used to create effects that automatically restart when key parameters change. This simplifies managing the lifecycle of effects such as coroutines or subscriptions that need to update when input data changes.
Purpose:
- Allows starting and canceling side effects when dependencies change.
- Ensures automatic restart of the effect without manually tracking changes.
Example of usage:
@Composable
fun MyComposable(userId: String) {
@Restartable
fun loadUserData() {
// Runs every time userId changes
LaunchedEffect(userId) {
val data = repository.getUserData(userId)
// update state
}
}
loadUserData()
}
In this example, when userId changes, the data loading effect automatically restarts, simplifying the code and making it more declarative.