Compose Multiplatform Lifecycle Tracker


A library to track the lifecycle of the application in Compose Multiplatform.
Setup
To use this library, you need some setup in your project.
Android
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)
{
.onCreate(savedInstanceState)
lifecycle.addObserver(observer)
setContent {
CompositionLocalProvider(LocalLifecycleTracker provides lifecycleTracker) {
MainView()
}
}
}
{
.onDestroy()
lifecycle.removeObserver(observer)
}
}
iOS
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()
}
}
}
Usage
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 {
println()
}
}
lifecycleTracker.addObserver(listener)
onDispose {
lifecycleTracker.removeObserver(listener)
}
}
}
Download

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")
}
}
}
}