Junior — Middle
Explain the working principle of DisposableEffect in the context of resource management in Jetpack Compose.
sobes.tech AI
Answer from AI
DisposableEffect in Jetpack Compose is used to manage the lifecycle of side effects that require cleanup or resource release when the state changes or the component is destroyed.
When you use DisposableEffect, you pass in keys that, when changed, cause the effect to be recreated. Inside DisposableEffect, you can perform some work (e.g., subscribing to a data stream), and in the onDispose block, you can clean up resources (unsubscribe, close connections, etc.).
Example:
DisposableEffect(key1 = someState) {
val listener = object : SomeListener {
override fun onEvent() { /* handle event */ }
}
someObject.addListener(listener)
onDispose {
someObject.removeListener(listener)
}
}
Thus, DisposableEffect helps prevent memory leaks and ensures proper resource cleanup when the state changes or the component is destroyed.