Broadcast<T> class
final
Broadcast (Single-Producer Multi-Consumer) Ring Channel
Features:
- Pub/Sub: All subscribers see all messages (subject to capacity).
- Ring Buffer: Fixed capacity power-of-two buffer. Oldest messages are overwritten.
- Lag Detection: Slow subscribers detect gaps and can skip lost data.
- Replay: New subscribers can "replay" history by starting from the tail.
Best suited for:
- High-frequency local event buses (UI events, telemetry).
- Scenarios where slow consumers should not block the producer.
Example
import 'dart:async';
import 'package:cross_channel/broadcast.dart';
Future<void> main() async {
// 1. Create a Broadcast (SPMC) ring channel
final (tx, broadcast) = Broadcast.channel<String>(1024);
// 2. Create multiple subscribers
final sub1 = broadcast.subscribe();
final sub2 = broadcast.subscribe();
// 3. Publisher
unawaited(Future.microtask(() async {
await tx.send('System Update Available');
await tx.send('Battery Low');
tx.close();
}));
// 4. Consumers receive the SAME messages concurrently
unawaited(Future.microtask(() async {
await for (final msg in sub1.stream()) {
print('UI Component 1 received: $msg');
}
}));
unawaited(Future.microtask(() async {
await for (final msg in sub2.stream()) {
print('UI Component 2 received: $msg');
}
}));
}
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
subscribe(
{int replay = 0}) → BroadcastReceiver< T> - Creates a new subscriber.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
channel<
T> (int capacity, {String? metricsId}) → BroadcastChannel< T> -
Creates a Broadcast channel with a fixed
capacity(must be power-of-two).