A library to track the lifecycle of the application in Compose Multiplatform.
To use this library, you need some setup in your project.
This library uses the androidx.lifecycle:lifecycle-runtime-ktx
library to track the lifecycle of the page. You need to add the following dependency to your build.gradle.kts
file.
val androidMain by getting {
dependencies {
implementation ("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
}
}
Then, you need to add the AndroidLifecycleEventObserver
to your Activity
or Fragment
to track the lifecycle of the page
and provide the LifecycleTracker
to the App
using CompositionLocalProvider
.
class MainActivity : AppCompatActivity() {
private val lifecycleTracker = LifecycleTracker()
private val observer = AndroidLifecycleEventObserver(lifecycleTracker)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(observer)
setContent {
CompositionLocalProvider(LocalLifecycleTracker provides lifecycleTracker) {
MainView()
}
}
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(observer)
}
}
For iOS, you need to set the 'LifecycleComposeUIVCDelegate' as the delegate of the UIComposeViewController
to track the lifecycle of the page
and provide the LifecycleTracker
to the App
using CompositionLocalProvider
.
fun MainViewController(): UIViewController {
val lifecycleTracker = LifecycleTracker()
return ComposeUIViewController({
delegate = LifecycleComposeUIVCDelegate(lifecycleTracker)
}) {
CompositionLocalProvider(LocalLifecycleTracker provides lifecycleTracker) {
App()
}
}
}
The usage is quite simple, you just need to create a 'LifecycleListener' and add it to the LifecycleTracker
.
@Composable
private fun LifecycleTest() {
val lifecycleTracker = LocalLifecycleTracker.current
DisposableEffect(Unit) {
val listener =
object : LifecycleObserver {
override fun onEvent(event: LifecycleEvent) {
println("Lifecycle: onEvent: $event")
}
}
lifecycleTracker.addObserver(listener)
onDispose {
lifecycleTracker.removeObserver(listener)
}
}
}
This library is available on Maven Central. You can add it to your project by adding the following dependency to your build.gradle.kts
file.
repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain {
dependencies {
api("io.github.kevinnzou:compose-multiplatform-lifecycle-tracker:1.0.0")
}
}
}
}