On the server-side, in addition to handling requests, Ktor exposes a mechanism to produce and consume global 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
monitor: ApplicationEvents instance, associated with the application environment, acts as the event dispatcher.
ApplicationEvents dispatches typed
EventDefinition<T> along with an object
You can get the monitor along with the application instance by executing
The simplified API for the
monitor: ApplicationEvents looks like this:
Ktor provides some predefined events that are dispatched by the engine:
Subscribing to events and raising them
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:
Using a lambda stored in a property:
Using a method reference:
If you want to create custom events and dispatch or raise them:
You can check the
CallLogging plugin source code that includes code subscribing to events from the application.