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()
val owner = requireNotNull(currentLifecycleOwner())
val scope = owner.lifecycleScope
// This job is canceled when the owner reaches DESTROYED.
scope.launch {
// Owner-local work
}
// STARTED/RESUMED runs the block; PAUSED/STOPPED cancels it.
val activeWork = whenActive(owner, key = "uniqueKey") {
// Active-only work
}
// Explicit component removal also cancels active work exactly once.
activeWork?.dispose()
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.