Skip to content

Runtime Events

Oliver Atkinson edited this page May 31, 2026 · 2 revisions

Runtime Events

SwiftLexicon is the runtime used by the swift generator. It provides generated values and async event streams keyed by generated lemmas.

Use it when vocabulary should drive event matching, analytics routing, UI state transitions, or reactive workflows.

Basic Event Stream

The ordinary spelling uses send and subscribe directly:

import SwiftLexicon

let events = Events()

let subscription = events.subscribe(where: { event in
	event.is(commerce.ux.type.action)
}) { event in
	print(event.description)
}

await events.send(Event(commerce.ui.product.card.buy)).value

subscription.cancel()
events.finish()

The >> operator is sugar for the same pattern:

let subscription = commerce.ux.type.action >> events.then { event in
	print(event.description)
}

commerce.ui.product.card.buy >> events

Use the explicit send form when you want to await delivery ordering with .value; the operator form is for fire-and-forward ergonomics.

Keyed Events

Generated lemmas can carry keyed values:

await events.send(Event(commerce.ui.product.card.buy["birthday_001"])).value

The operator sugar is:

commerce.ui.product.card.buy["birthday_001"] >> events

The payload is JSON-backed. Decode it through JSONDecoder:

let subscription = events.subscribe(where: { event in
	event.is(commerce.ui.product.card.buy)
}) { event in
	guard let value: String = try? event[type: String.self] else {
		return
	}
	print(value)
}

Match by Type

If generated lemmas conform to the generated I_commerce_ux_type_action protocol, subscribe to that type for broad handling:

let subscription = events.subscribe(where: { event in
	event.is(I_commerce_ux_type_action.self)
}) { event in
	print("action:", event.description)
}

The operator sugar is:

let subscription = I_commerce_ux_type_action.self >> events.then { event in
	print("action:", event.description)
}

This lets different UI events share handling through vocabulary types instead of switch statements over strings.

Snapshot

Events expose a sendable snapshot:

let snapshot = event.snapshot

print(snapshot.id)
print(snapshot.description)
print(snapshot.lemma)
print(snapshot.values)

Use snapshots at concurrency boundaries or when storing an event log.

Practical Pattern

  1. Define product actions and state transitions in .lexicon.
  2. Generate Swift with --type swift.
  3. Use generated lemmas when sending events.
  4. Subscribe by concrete lemma for narrow behavior.
  5. Subscribe by generated type for broad behavior.
  6. Persist exact IDs and JSON values, not generated class names.

The generated source is the compile-time surface. The dot-path ID is the stable runtime contract.

Clone this wiki locally