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:

    1. val ApplicationStopPreparing: EventDefinition<ApplicationEnvironment>
    2. val ApplicationStopping: EventDefinition<Application>
    3. 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:

    1. application.environment.monitor.subscribe(ApplicationStarting, starting) // subscribe
    2. application.environment.monitor.unsubscribe(ApplicationStarting, starting) // unsubscribe

    Using a method reference:

    If you want to create custom events and dispatch or raise them:

    1. class MySubject
    2. monitor.raise(MyEventDefinition, MySubject())

    You can check the that includes code subscribing to events from the application.