Typed event bus with Stream subscriptions, sticky events, and scoped lifecycle
dart pub add philiprehberger_event_busTyped event bus with Stream subscriptions, sticky events, and scoped lifecycle
Add to your pubspec.yaml:
dependencies:
philiprehberger_event_bus: ^0.1.0
Then run:
dart pub get
import 'package:philiprehberger_event_bus/event_bus.dart';
final bus = EventBus();
bus.on<String>().listen((event) {
print('Received: $event');
});
bus.fire('hello');
class UserLoggedIn {
final String userId;
UserLoggedIn(this.userId);
}
bus.on<UserLoggedIn>().listen((event) {
print('User logged in: ${event.userId}');
});
bus.fire(UserLoggedIn('user-123'));
Sticky events are stored and replayed to new subscribers:
bus.fireSticky(UserLoggedIn('user-456'));
// New listener immediately receives the last sticky event
bus.on<UserLoggedIn>().listen((event) {
print('Got sticky: ${event.userId}');
});
// Retrieve the last sticky event directly
final last = bus.lastSticky<UserLoggedIn>();
// Clear when no longer needed
bus.clearSticky<UserLoggedIn>();
bus.dispose();
After calling dispose(), no more events can be fired or received.
| Method | Description |
|---|---|
fire<T>(T event) | Dispatch an event to all listeners of type T |
on<T>() | Subscribe to events of type T, returns Stream<T> |
fireSticky<T>(T event) | Dispatch a sticky event that replays to new subscribers |
lastSticky<T>() | Get the last sticky event of type T, or null |
clearSticky<T>() | Remove the stored sticky event of type T |
dispose() | Close the bus and release all resources |
dart pub get
dart analyze --fatal-infos
dart test
If you find this project useful: