package com.example.lifecycleawareness
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LifecycleDemoScreen(lifecycle = lifecycle)
}
}
}
@Composable
fun LifecycleDemoScreen(lifecycle: Lifecycle) {
val events = remember { mutableStateListOf<String>() }
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
when(event) {
Lifecycle.Event.ON_CREATE -> events.add("onCreate")
Lifecycle.Event.ON_START -> events.add("onStart")
Lifecycle.Event.ON_RESUME -> events.add("onResume")
Lifecycle.Event.ON_PAUSE -> events.add("onPause")
Lifecycle.Event.ON_STOP -> events.add("onStop")
Lifecycle.Event.ON_DESTROY -> events.add("onDestroy")
else -> {}
}
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
}
}
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Column {
LazyColumn(modifier = Modifier.weight(1f)) {
items(events) { event ->
Text(text = "- $event")
}
}
Button(onClick = { events.clear() }) {
Text(text = "Clear Events")
}
}
}
}This solution uses Jetpack Compose to build the UI and AndroidX Lifecycle components to observe lifecycle events.
We create a mutableStateListOf to hold event names so the UI updates automatically when the list changes.
The LifecycleEventObserver listens to lifecycle changes and adds the event name to the list.
We use DisposableEffect to add the observer when the composable enters composition and remove it when it leaves, avoiding leaks.
The UI shows the events in a scrollable list and a button to clear the list.