### Example Usage: Basic Event Handling (Dart) Source: https://github.com/matserdam/typed_bus/blob/main/README.md A complete example demonstrating the core functionality of TypedBus: registering an event, subscribing to it, and publishing a typed payload. This illustrates the type-safe communication flow within a Dart application. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Register events tBE.registerEvent('eventName'); // Subscribe to events tB.subscribe('eventName').listen((data) { print('Received eventName: $data'); }); tB.publish('eventName', 'Hello world!'); } ``` -------------------------------- ### Dart: TypedBus API - TypedBusEvents Registration Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Provides examples of using the TypedBusEvents (tBE) singleton to register events with their specific payload types. This is a crucial step before any event can be subscribed to or published, ensuring type safety. ```dart import 'package:typed_bus/typed_bus.dart'; // Register an event with a String payload tBE.registerEvent('user:login'); // Register an event with an integer payload tBE.registerEvent('notification:count'); // Register an event with a custom object payload // class UserProfile { ... } tBE.registerEvent('profile:updated'); // Register an event with a dynamic payload tBE.registerEvent('generic:message'); ``` -------------------------------- ### Dart Validate Event Type with Typed_bus Source: https://context7.com/matserdam/typed_bus/llms.txt Shows how to use `tBE.validateEvent()` in typed_bus to check if an event is registered and if it matches the expected type. The examples cover successful validation for a correctly typed registered event, a type mismatch error when validating against the wrong type, and an error for an unregistered event. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { tBE.registerEvent('config_updated'); tBE.registerEvent('timer_tick'); // Validate correct type - returns normally try { tBE.validateEvent('config_updated'); print('Validation passed for config_updated'); } catch (e) { print('Validation failed: $e'); } // Output: Validation passed for config_updated // Validate wrong type - throws ArgumentError try { tBE.validateEvent('config_updated'); // Registered as String print('This will not print'); } catch (e) { print('Type mismatch: $e'); } // Output: Type mismatch: ArgumentError: Type mismatch for event "config_updated" // Validate unregistered event - throws ArgumentError try { tBE.validateEvent('unknown_event'); } catch (e) { print('Unregistered: $e'); } // Output: Unregistered: ArgumentError: Event "unknown_event" is not registered. } ``` -------------------------------- ### Get Event Type using Dart Source: https://context7.com/matserdam/typed_bus/llms.txt Retrieves the registered type for a given event name using `tBE.getEventType()`. Returns null if the event is not registered. Useful for conditional event handling. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { tBE.registerEvent('notification'); tBE.registerEvent('count'); tBE.registerEvent('flexible'); // Get registered event types Type? notificationType = tBE.getEventType('notification'); print('notification type: $notificationType'); // String Type? countType = tBE.getEventType('count'); print('count type: $countType'); // int Type? flexibleType = tBE.getEventType('flexible'); print('flexible type: $flexibleType'); // dynamic // Query unregistered event returns null Type? unknownType = tBE.getEventType('does_not_exist'); print('unknown type: $unknownType'); // null // Use case: conditional event handling based on type String eventName = 'notification'; Type? eventType = tBE.getEventType(eventName); if (eventType == String) { print('This event expects String payloads'); } else if (eventType == null) { print('Event not registered'); } } ``` -------------------------------- ### Fetching Package Dependencies (Bash) Source: https://github.com/matserdam/typed_bus/blob/main/README.md Command-line instruction to fetch the project's dependencies, including TypedBus, after updating the `pubspec.yaml` file. This command downloads and links the necessary packages for the project to use. ```bash flutter pub get ``` -------------------------------- ### Multiple Subscribers Pattern using Dart Source: https://context7.com/matserdam/typed_bus/llms.txt Demonstrates how multiple independent subscribers can listen to the same event concurrently. A single event publication will be received by all active subscribers for that event. ```dart import 'package:typed_bus/typed_bus.dart'; class Logger { void log(String message) => print('[LOG] $message'); } class Analytics { void track(String event) => print('[ANALYTICS] Event: $event'); } class Notifier { void notify(String message) => print('[NOTIFICATION] $message'); } void main() async { // Register event tBE.registerEvent('user_action'); // Multiple independent subscribers Logger logger = Logger(); Analytics analytics = Analytics(); Notifier notifier = Notifier(); // Each subscriber receives the same events tB.subscribe('user_action').listen((action) { logger.log('User performed: $action'); }); tB.subscribe('user_action').listen((action) { analytics.track(action); }); tB.subscribe('user_action').listen((action) { notifier.notify('Action completed: $action'); }); // Single publish reaches all subscribers tB.publish('user_action', 'button_clicked'); // Output: // [LOG] User performed: button_clicked // [ANALYTICS] Event: button_clicked // [NOTIFICATION] Action completed: button_clicked await Future.delayed(Duration(milliseconds: 100)); tB.publish('user_action', 'form_submitted'); // Output: // [LOG] User performed: form_submitted // [ANALYTICS] Event: form_submitted // [NOTIFICATION] Action completed: form_submitted } ``` -------------------------------- ### Dart Custom Type Events with Typed_bus Source: https://context7.com/matserdam/typed_bus/llms.txt Demonstrates using custom Dart classes (TodoItem, User) as event payloads with typed_bus. It covers registering custom event types, subscribing to them, and publishing events with instances of these custom classes. This approach ensures strong typing for complex data structures. ```dart import 'package:typed_bus/typed_bus.dart'; class TodoItem { String description; bool isDone; TodoItem({required this.description, required this.isDone}); @override String toString() { return 'TodoItem(description: $description, isDone: $isDone)'; } } class User { final String id; final String name; final String email; User({required this.id, required this.name, required this.email}); } void main() { // Register custom types tBE.registerEvent('todo_toggled'); tBE.registerEvent('user_created'); // Subscribe to custom type events tB.subscribe('todo_toggled').listen((TodoItem item) { item.isDone = !item.isDone; print('Toggled: ${item}'); }); tB.subscribe('user_created').listen((User user) { print('Welcome ${user.name}! (${user.email})'); // Send welcome email, update database, etc. }); // Publish custom type events tB.publish( 'todo_toggled', TodoItem(description: 'Write documentation', isDone: false) ); // Output: Toggled: TodoItem(description: Write documentation, isDone: true) tB.publish( 'user_created', User(id: '123', name: 'Alice', email: 'alice@example.com') ); // Output: Welcome Alice! (alice@example.com) } ``` -------------------------------- ### Dart: Registering Application-Wide Events Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Illustrates a common pattern for registering all application events in a single location, typically at application startup. This approach helps avoid duplicate registrations and ensures all events are defined before they are used. ```dart import 'package:typed_bus/typed_bus.dart'; void registerAppEvents() { tBE.registerEvent('auth:signed_in'); tBE.registerEvent('cart:count_changed'); } ``` -------------------------------- ### Dart Dynamic Payload Events with Typed_bus Source: https://context7.com/matserdam/typed_bus/llms.txt Illustrates handling events with varying payload types using `dynamic` in typed_bus. It shows how to register an event for `dynamic` type, subscribe to it, and then publish different data types (Map, String, int) to the same event. The subscriber uses type checking (`is`) to handle the different payloads. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Register with dynamic type tBE.registerEvent('analytics_event'); // Subscribe to dynamic events tB.subscribe('analytics_event').listen((data) { if (data is Map) { print('Logging map event: ${data}'); } else if (data is String) { print('Logging string event: $data'); } else if (data is int) { print('Logging numeric event: $data'); } else { print('Logging unknown event: $data'); } }); // Publish various types to the same event tB.publish('analytics_event', {'action': 'click', 'button': 'submit'}); // Output: Logging map event: {action: click, button: submit} tB.publish('analytics_event', 'page_view'); // Output: Logging string event: page_view tB.publish('analytics_event', 42); // Output: Logging numeric event: 42 tB.publish('analytics_event', ['item1', 'item2']); // Output: Logging unknown event: [item1, item2] } ``` -------------------------------- ### Dart WildFire Unvalidated Publishing with Typed_bus Source: https://context7.com/matserdam/typed_bus/llms.txt Explains and demonstrates the `wildFire()` method in typed_bus for publishing events without type validation, alongside `subscribeRaw()` for accessing the raw event stream. This is useful for debugging or scenarios where type safety is less critical. It shows publishing various types to an event registered as `dynamic` and observing their runtime types. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Register event with specific type tBE.registerEvent('raw_data'); // Subscribe with raw stream (no type casting) tB.subscribeRaw('raw_data').listen((data) { print('Raw data received: $data (${data.runtimeType})'); }); // Publish without type validation using wildFire tB.wildFire('raw_data', {'key': 'value'}); // Output: Raw data received: {key: value} (_Map) tB.wildFire('raw_data', 'some string'); // Output: Raw data received: some string (String) tB.wildFire('raw_data', [1, 2, 3]); // Output: Raw data received: [1, 2, 3] (List) // wildFire bypasses type checking entirely // Useful for debugging or when type safety is not critical } ``` -------------------------------- ### YAML Configuration for TypedBus Dependency Source: https://github.com/matserdam/typed_bus/blob/main/README.md Specifies how to add the TypedBus package as a dependency in your Dart or Flutter project's `pubspec.yaml` file. This is the standard method for including external libraries managed by Dart's package system. ```yaml dependencies: typed_bus: ^1.0.0 ``` -------------------------------- ### Publish Typed Events with TypedBus (Dart) Source: https://context7.com/matserdam/typed_bus/llms.txt Publishes events with typed payloads using `tB.publish()` to notify subscribers. Type mismatches during publishing or attempting to publish to an unregistered event will result in an `ArgumentError`. Ensure events are registered before publishing. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Setup tBE.registerEvent('message_sent'); tB.subscribe('message_sent').listen((msg) { print('Received: $msg'); }); // Publish events tB.publish('message_sent', 'Hello, World!'); // Output: Received: Hello, World! tB.publish('message_sent', 'Another message'); // Output: Received: Another message // Type mismatch when publishing throws ArgumentError try { tB.publish('message_sent', 42); // Registered as String } catch (e) { print('Error: $e'); // Type mismatch for event "message_sent" } // Publishing to unregistered event throws ArgumentError try { tB.publish('unknown_event', 'data'); } catch (e) { print('Error: $e'); // Event "unknown_event" is not registered. } } ``` -------------------------------- ### Dart: TypedBus API - Raw Subscribe and Unsafe Publish Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Demonstrates the `subscribeRaw` and `wildFire` methods of TypedBus. `subscribeRaw` provides a stream of dynamic type, useful when explicit type casting is not desired. `wildFire` allows publishing events without any type validation, which should be used with caution. ```dart import 'package:typed_bus/typed_bus.dart'; // Assuming 'some_event' is registered // Subscribe to a raw dynamic stream tB.subscribeRaw('some_event').listen((data) { // data is of type dynamic print('Received raw data: $data'); }); // Publish an event without validation (use with caution!) tB.wildFire('some_event', 'Unvalidated data'); tB.wildFire('some_event', 456); ``` -------------------------------- ### Subscribe to Typed Events with TypedBus (Dart) Source: https://context7.com/matserdam/typed_bus/llms.txt Subscribes to registered events using `tB.subscribe()`, which returns a typed Stream. This allows listening for specific event payloads. Error handling can be provided via the `onError` and `onDone` callbacks. Type mismatches during subscription or subscribing to unregistered events will throw `ArgumentError`. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Register event first tBE.registerEvent('user_logged_in'); // Subscribe and listen for events tB.subscribe('user_logged_in').listen((String username) { print('User logged in: $username'); // Perform actions like updating UI, fetching user data, etc. }); // Subscribe with error handling tBE.registerEvent('score_updated'); tB.subscribe('score_updated').listen( (int score) { print('New score: $score'); }, onError: (error) { print('Error receiving score: $error'); }, onDone: () { print('Score stream closed'); }, ); // Type mismatch throws ArgumentError at subscription time try { tB.subscribe('user_logged_in'); // Registered as String } catch (e) { print('Error: $e'); // Type mismatch for event "user_logged_in" } // Subscribing to unregistered event throws ArgumentError try { tB.subscribe('unregistered_event'); } catch (e) { print('Error: $e'); // Event "unregistered_event" is not registered. } } ``` -------------------------------- ### Dispose and Cleanup Resources using Dart Source: https://context7.com/matserdam/typed_bus/llms.txt Cleans up all event bus resources by closing stream controllers using `tB.dispose()`. This is crucial for preventing memory leaks and should be called during application shutdown or widget disposal. ```dart import 'package:typed_bus/typed_bus.dart'; import 'dart:async'; void main() async { // Setup events and subscriptions tBE.registerEvent('app_event'); StreamSubscription subscription = tB.subscribe('app_event').listen((data) { print('Received: $data'); }); // Publish some events tB.publish('app_event', 'Event 1'); tB.publish('app_event', 'Event 2'); await Future.delayed(Duration(milliseconds: 100)); // Cancel specific subscription await subscription.cancel(); // Dispose all controllers when shutting down tB.dispose(); print('All event bus resources cleaned up'); // After dispose, you can re-register and reuse tBE.registerEvent('new_event'); tB.subscribe('new_event').listen((data) { print('After dispose: $data'); }); tB.publish('new_event', 'Fresh start'); await Future.delayed(Duration(milliseconds: 100)); // Always dispose when your app shuts down to prevent memory leaks tB.dispose(); } ``` -------------------------------- ### Register Event Types with TypedBus (Dart) Source: https://context7.com/matserdam/typed_bus/llms.txt Registers event names with their expected payload types using `tBE.registerEvent()`. This step is crucial before publishing or subscribing. It supports basic types, custom types, and dynamic payloads. Attempting to register the same event twice will result in an `ArgumentError`. ```dart import 'package:typed_bus/typed_bus.dart'; void main() { // Register basic types tBE.registerEvent('user_logged_in'); tBE.registerEvent('counter_updated'); tBE.registerEvent('settings_changed'); // Register custom types tBE.registerEvent('todo_toggled'); // Register for dynamic payloads tBE.registerEvent('generic_event'); // Attempting to register the same event twice throws ArgumentError try { tBE.registerEvent('user_logged_in'); } catch (e) { print('Error: $e'); // ArgumentError: Event "user_logged_in" is already registered. } } class TodoItem { String description; bool isDone; TodoItem({required this.description, required this.isDone}); } ``` -------------------------------- ### Dart: TypedBus API - TypedBus Subscribe and Publish Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Illustrates the core functions of the TypedBus (tB) singleton: `subscribe` to receive events as typed streams and `publish` to send events with typed data. These methods enforce type checking against the registered events in TypedBusEvents. ```dart import 'package:typed_bus/typed_bus.dart'; // Assuming events are already registered with tBE // Subscribe to a String event tB.subscribe('some_string_event').listen((data) { print('Received string: $data'); }); // Publish a String event tB.publish('some_string_event', 'Data'); // Subscribe to an int event tB.subscribe('some_int_event').listen((data) { print('Received int: $data'); }); // Publish an int event tB.publish('some_int_event', 123); ``` -------------------------------- ### Dart: Using Custom Payload Types with TypedBus Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Shows how to define and use custom classes as payload types for events in TypedBus. This allows for structured data transfer between event publishers and subscribers, enhancing type safety and code readability. ```dart import 'package:typed_bus/typed_bus.dart'; class TodoItem { final String description; final bool isDone; TodoItem({required this.description, required this.isDone}); } void main() { tBE.registerEvent('todo:toggle'); tB.subscribe('todo:toggle').listen((item) { print('Toggling todo: ${item.description}'); }); tB.publish('todo:toggle', TodoItem(description: 'Buy milk', isDone: false)); } ``` -------------------------------- ### Subscribe to Event with TypedBus (Dart) Source: https://github.com/matserdam/typed_bus/blob/main/README.md Subscribes to a specific event and listens for incoming payloads of the registered type ``. The `listen` method returns a Stream that emits the typed data when the event is published. Ensures type safety by only receiving payloads matching the specified type. ```dart tB.subscribe('event1').listen((String data) { print('Received Event 1: $data'); }); ``` -------------------------------- ### Publishing Dynamic Payloads (Dart) Source: https://github.com/matserdam/typed_bus/blob/main/README.md Enables the use of `dynamic` as an event payload type when the data structure is not fixed. This allows publishing and subscribing to events with varying data types, such as JSON objects or primitive values, under a single event name. ```dart tBE.registerEvent('dynamic_event'); tB.subscribe('dynamic_event').listen((data) { print('Dynamic event received: $data'); }); tB.publish('dynamic_event', {'key': 'value'}); tB.publish('dynamic_event', 12345); tB.publish('dynamic_event', 'a string'); ``` -------------------------------- ### Dart: TypedBus API - Disposing the Bus Source: https://github.com/matserdam/typed_bus/blob/main/llms.txt Shows how to use the `dispose` method on the TypedBus (tB) singleton. Calling dispose closes all internal StreamControllers, effectively stopping all active event streams and releasing resources. Note that this does not clear the event registry in TypedBusEvents. ```dart import 'package:typed_bus/typed_bus.dart'; // ... (subscribe and publish operations) ... // Dispose of the bus to close all streams tB.dispose(); ``` -------------------------------- ### Publish Event with TypedBus (Dart) Source: https://github.com/matserdam/typed_bus/blob/main/README.md Publishes a strongly-typed event globally. The generic type `` must match the type registered for the event, and `data` is the payload to be sent. This function ensures that only payloads of the correct type are dispatched, preventing runtime errors. ```dart tB.publish('event1', "Hello world!"); ``` -------------------------------- ### Register Event with TypedBusEvents (Dart) Source: https://github.com/matserdam/typed_bus/blob/main/README.md Registers a new event with its expected payload type. This must be done before subscribing to or publishing the event. The generic type `` specifies the expected data type for the event's payload. ```dart tBE.registerEvent('event1'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.