Typed Event Bus
A type-safe view over an EventBus that restricts post and subscribe to a specific event hierarchy E. Provides compile-time enforcement that only subtypes of E can be posted or subscribed to through this interface.
Obtaining an instance
Kotlin (reified):
sealed interface NetworkEvent : Event
class PacketReceived(val bytes: ByteArray) : NetworkEvent
class ConnectionLost(val reason: String) : NetworkEvent
val networkBus = EventBus().typed<NetworkEvent>()
networkBus.post(PacketReceived(bytes)) // OK
// networkBus.post(ButtonClickEvent()) // compile errorJava (class token):
TypedEventBus<NetworkEvent> networkBus =
TypedEventBusFactory.typed(underlying, NetworkEvent.class);Sealed hierarchies
The compile-time guarantee is strongest when E is a sealed interface or sealed class; no external type can satisfy T : E, so the constraint cannot be circumvented from outside the module.
Wildcard listeners
subscribeAll accepts (Event) -> Unit rather than (E) -> Unit because wildcard handlers observe the raw underlying bus and may see events outside this typed view if the underlying EventBus is shared between multiple typed views.
Underlying bus
TypedEventBus<E> is a thin adapter with zero runtime overhead beyond a single delegation. The underlying bus is accessible via delegate for operations not covered by this interface (e.g. EventBus.subscribeStatic, EventBus.unsubscribeAll). Handlers registered on either the typed view or the underlying bus are visible to both.
Parameters
The root event type this bus accepts. All posted events must be subtypes of E.
Properties
Functions
Returns true if at least one handler is registered for eventClass or any supertype.
Returns true if at least one handler is registered for T or any of its supertypes.
Registers all instance methods on subscriber annotated with @Subscribe.
Registers a java.util.function.Consumer handler for event type T and returns a Subscription token for removal.
Registers a lambda handler for event type T and returns a Subscription token. Hidden from Java; Java callers use the java.util.function.Consumer overload.
Registers a lambda handler for event type T on this TypedEventBus.
Registers a wildcard java.util.function.Consumer handler that fires for every event posted to the underlying bus. Returns a Subscription token for removal.
Registers a wildcard handler that fires for every event posted to the underlying bus, regardless of type. Returns a Subscription token for removal. Hidden from Java; Java callers use the java.util.function.Consumer overload.
Registers a wildcard handler on this TypedEventBus with Priority.NORMAL default.
Registers all static methods on klass annotated with @Subscribe.
Removes all handlers previously registered by subscribe for the given subscriber.
Removes all static handlers previously registered for klass.