Skip to content

Instantly share code, notes, and snippets.

@yoobi
Created September 30, 2022 19:54
Show Gist options
  • Save yoobi/ccf927216a1d9ab6b186a7196a7093e0 to your computer and use it in GitHub Desktop.
Save yoobi/ccf927216a1d9ab6b186a7196a7093e0 to your computer and use it in GitHub Desktop.
Difference between DisposableEffect and DefaultLifecycleObserver
class CustomClass(
private val text: String,
private val lifecycleOwner: LifecycleOwner
): DefaultLifecycleObserver {
init {
lifecycleOwner.lifecycle.addObserver(this)
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
Log.e("CustomClass", "$text -- onCreate")
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
Log.e("CustomClass", "$text -- onStart")
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
Log.e("CustomClass", "$text -- onResume")
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
Log.e("CustomClass", "$text -- onPause")
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
Log.e("CustomClass", "$text -- onStop")
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
Log.e("CustomClass", "$text -- onDestroy")
lifecycleOwner.lifecycle.removeObserver(this)
}
fun release() {
lifecycleOwner.lifecycle.removeObserver(this)
}
}
class MainActivity : ComponentActivity() {
fun generateRandomString() = java.util.UUID.randomUUID().toString().substringBefore("-")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTheme {
var text by remember { mutableStateOf(generateRandomString()) }
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
RandomText(text = text)
Button(onClick = { text = generateRandomString() }) {
Text(text = "Change text")
}
}
}
}
}
}
}
// When changing to a new text, onPause, onStop, onDestroy are not called
// If c?.release() is commented and you've tapped the button a few time,
// when putting the app in background all the CustomClass are entering onPause, onStop
@Composable
fun RandomText(text: String) {
val lifecycleOwner = LocalLifecycleOwner.current
var c: CustomClass? = null
Text(text)
DisposableEffect(text, lifecycleOwner) {
c = CustomClass(text, lifecycleOwner)
Log.e("RandomText-Composable", "$text -- in DisposableEffect")
onDispose {
c?.release()
c = null
Log.e("RandomText-Composable", "$text -- in onDispose")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment