toChannel<T> method

(dynamic, dynamic) toChannel<T>(
  1. ChannelType type, {
  2. int? capacity,
  3. DropPolicy policy = DropPolicy.block,
  4. OnDrop<T>? onDrop,
  5. bool chunked = true,
  6. bool strict = true,
})

Convert port messages to a channel with unified API.

Modern, unified approach that replaces toMpsc and toMpmc. When strict == true, the port is closed on unexpected message types.

Parameters:

  • type: Channel type (mpsc or mpmc)
  • capacity: Buffer size (null = unbounded, 0 = rendezvous)
  • policy: Drop policy for bounded channels
  • onDrop: Optional callback for dropped items
  • chunked: Use optimized chunked buffer
  • strict: Close port on type mismatches

Example:

// Web Worker communication
final worker = Worker('processor.js');
final channel = MessageChannel();
worker.postMessage({'port': channel.port1}, [channel.port1]);

final (tx, rx) = channel.port2.toChannel<ProcessingTask>(
  type: ChannelType.mpsc,
  capacity: 500,
);

// Send tasks to worker
await tx.send(ProcessingTask('heavy_computation', data));

Implementation

(dynamic, dynamic) toChannel<T>(
  ChannelType type, {
  int? capacity,
  DropPolicy policy = DropPolicy.block,
  OnDrop<T>? onDrop,
  bool chunked = true,
  bool strict = true,
}) {
  switch (type) {
    case ChannelType.mpsc:
      return toMpsc<T>(
        capacity: capacity,
        policy: policy,
        onDrop: onDrop,
        chunked: chunked,
        strict: strict,
      );
    case ChannelType.mpmc:
      return toMpmc<T>(
        capacity: capacity,
        policy: policy,
        onDrop: onDrop,
        chunked: chunked,
        strict: strict,
      );
  }
}