Summon provides a lifecycle management system that works across different UI frameworks. This guide explains how to use and extend this system.
The lifecycle system consists of:
LifecycleOwner class that manages lifecycle states// Get the current lifecycle owner
val lifecycleOwner = currentLifecycleOwner()
// Create a lifecycle-aware component
val component = lifecycleAware(lifecycleOwner) {
onResume {
println("Component is resumed")
}
onPause {
println("Component is paused")
}
onDestroy {
println("Component is destroyed")
}
}
// Don't forget to dispose when no longer needed
component.dispose()
// Get a coroutine scope tied to the lifecycle
val scope = lifecycleCoroutineScope()
// Launch a coroutine that's cancelled when the lifecycle owner is destroyed
scope.launch {
// Long-running operation
}
// Or use the whenActive helper
whenActive(key = "uniqueKey") {
// This block is only executed when the lifecycle is in STARTED or RESUMED state
// and is automatically cancelled when it becomes inactive
}
The JVM implementation automatically detects the UI framework you're using and sets up the appropriate lifecycle integration.
You can create and register your own framework integration:
// Create a custom integration
class MyFrameworkIntegration : LifecycleIntegration {
override fun setup(lifecycleOwner: JvmLifecycleOwner) {
// Connect lifecycle events to your framework
// Example:
myFramework.onShow {
lifecycleOwner.simulateStart()
lifecycleOwner.simulateResume()
}
myFramework.onHide {
lifecycleOwner.simulatePause()
}
myFramework.onClose {
lifecycleOwner.simulateStop()
lifecycleOwner.simulateDestroy()
}
}
}
// Register your integration
JvmLifecycleOwner.registerIntegration(MyFrameworkIntegration())
In some cases, you may want to manually control the lifecycle states:
// Get the JVM lifecycle owner
val jvmLifecycleOwner = JvmLifecycleOwner.instance
// Manually trigger lifecycle events
jvmLifecycleOwner.simulateStart()
jvmLifecycleOwner.simulateResume()
jvmLifecycleOwner.simulatePause()
jvmLifecycleOwner.simulateStop()
jvmLifecycleOwner.simulateDestroy()
The system supports the following lifecycle states:
CREATED: The component has been created but is not visibleSTARTED: The component is starting but not yet interactiveRESUMED: The component is visible and interactivePAUSED: The component is visible but not interactiveSTOPPED: The component is not visibleDESTROYED: The component has been destroyedWhen your application starts:
JvmLifecycleFactory checks which UI frameworks are available in the classpathThis allows your code to respond to lifecycle events without being directly tied to any specific UI framework.