Handling application-level events
For example, when the application is starting, has started, or has stopped, an event is generated and raised.You can subscribe to or unsubscribe from these events and trigger code execution.The instance, associated with the application environment, acts as the event dispatcher.
The ApplicationEvents
dispatches typed EventDefinition<T>
along with an object T
.
You can get the monitor along with the application instance by executing application.environment.monitor
.
Ktor provides some predefined events that are dispatched by the engine:
val ApplicationStopPreparing: EventDefinition<ApplicationEnvironment>
val ApplicationStopping: EventDefinition<Application>
val ApplicationStopped: EventDefinition<Application>
You can subscribe to events by calling the subscribe
method from the monitor.The subscribe method returns a DisposableHandle
that you can call to cancel the subscription.Additionally, you can call the unsubscribe
method with the same method handle to cancel the subscription.
Using the disposable:
application.environment.monitor.subscribe(ApplicationStarting, starting) // subscribe
application.environment.monitor.unsubscribe(ApplicationStarting, starting) // unsubscribe
Using a method reference:
If you want to create custom events and dispatch or raise them:
class MySubject
monitor.raise(MyEventDefinition, MySubject())
You can check the feature source code that includes code subscribing to events from the application.