OneShot class
One-shot channels - Promise-like single-value delivery with advanced semantics.
Specialized channels for delivering exactly one value, similar to futures but with more flexible consumption patterns. Perfect for request-response scenarios, async initialization, and promise-like patterns.
Core Features
- Single-value semantics: Exactly one value can be sent
- Flexible consumption: Choose between consume-once or multi-reader patterns
- Promise-like behavior: Similar to futures but with channel semantics
- Type-safe results: Explicit success/failure handling
- Zero buffering: Direct producer-to-consumer handoff
Consumption Modes
consumeOnce: true (Default Promise Behavior)
- First receiver gets the value and consumes it
- Channel disconnects immediately after consumption
- Subsequent receivers get
RecvErrorDisconnected - Perfect for request-response patterns
consumeOnce: false (Broadcast Promise)
- All receivers (current and future) get the same value
- Value remains available until explicitly handled
- Multiple receivers can read the same result
- Perfect for initialization values or shared results
Example
import 'dart:async';
import 'package:cross_channel/oneshot.dart';
Future<void> main() async {
// 1. Create a one-shot promise channel
// `consumeOnce: true` means only the first receiver gets the value.
final (responseTx, responseRx) = OneShot.channel<String>(consumeOnce: true);
// 2. Server Side (Promise resolution)
unawaited(Future.microtask(() async {
// Send exactly one response
await responseTx.send('Operation completed successfully');
}));
// 3. Client Side
final result = await responseRx.recv();
if (result is RecvOk<String>) {
print('Response: ${result.value}');
} else if (result is RecvErrorDisconnected) {
print('Server disconnected without answering');
}
}
Constructors
- OneShot()
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
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
channel<
T> ({bool consumeOnce = false, String? metricsId}) → OneShotChannel< T>