Skip to content
Thiago Santos edited this page Aug 15, 2024 · 1 revision

Important

This module is not related to Ktor Application monitoring.

Some applications need to produce events to track user breadcumb or something related to observability. You can create a routing plugin to track any called route like CallLogging does. But it is not enough to other behaviors like emit a custom event.

So the events module is a extension of the core routing but instead of paths it route is based in names.

sourceSets {
    commonMain.dependencies {
        implementation("dev.programadorthi.routing:events:$version")
    }
}

Observability setup

Define a route handler

val router = routing {
    event(name = "event_name") {
        // Handle any call to the "event_name" event
    }
}

Calling events

router.emitEvent(name = "event_name")

Unregister events

router.unregisterEvent(name = "event_name")

Handling errors to events

Checkout the Status Pages to how catch errors during routing to an event.

Passing parameters

router.emitEvent(
    name = "event_name",
    parameters = parametersOf("id", "123"),
)

Nested events

Events module doesn't support nesting routes or events because it not works as a path based routing and to avoid bad behaviors to the structure

Nested Routing events

val applicationRouter = routing { 
    event(name = "first_time") {
        // ...
    }
}

val featureARouter = routing(rootPath = "/feature-a", parent = applicationRouter) {
    event(name = "home_opened") {
        // ...
    }
}

val featureBRouter = routing(rootPath = "/feature-b", parent = applicationRouter) {
    event(name = "option_choosed") {
        // ...
    }
}

// tracking B events
featureBRouter.emitEvent(name = "option_choosed")

// tracking applications events from B
featureBRouter.emitEvent(name = "first_time")

// tracking A events from application
applicationRouter.emitEvent(name = "/feature-a/home_opened")

Now just plug you observability platform to the event handler and report each emitted event.

Type-safe Events

There is a events-resources module that provides a way to handler and emit events in a type-safe way. It is an extension of resources module adapted to work with events.

sourceSets {
    commonMain.dependencies {
        implementation("dev.programadorthi.routing:events-resources:$version")
    }
}

Install Event Resources

val router = routing {
    install(EventResources)
    // ...
}

Create an event resource classes

@Event("app_start")
class AppStart

@Event("screen_view")
class ScreenView(val screenName: String)

Define event handlers

val router = routing {
    event<AppStart> {
        // ...
    }

    event<ScreenView> {
        // ...
    }
}

Calling event resources

router.emitEvent(
    name = "screen_view",
    parameters = parametersOf("screenName", "screen01")
)
// or just
router.emitEvent(ScreenView(screenName = "screen01"))

Checkout the Type‐safe routing to more resources related behaviors.