createSampleChannel static method

(ReceivePort, StreamController<Sample>) createSampleChannel()

Sets up a ReceivePort and StreamController pair that parses incoming NativePort sample messages into Sample objects.

Returns (ReceivePort, StreamController<Sample>). The caller is responsible for passing receivePort.sendPort.nativePort to the C shim and for cleanup on failure.

Implementation

static (ReceivePort, StreamController<Sample>) createSampleChannel() {
  final receivePort = ReceivePort();
  final controller = StreamController<Sample>();

  receivePort.listen((dynamic message) {
    if (message == null) {
      receivePort.close();
      controller.close();
    } else if (message is List) {
      final keyExpr = message[0] as String;
      final payloadBytes = message[1] as Uint8List;
      final kind = message[2] as int;
      final attachmentBytes = message[3] as Uint8List?;
      final encoding = message.length > 4 ? message[4] as String? : null;

      final sample = Sample(
        keyExpr: keyExpr,
        payload: utf8.decode(payloadBytes, allowMalformed: true),
        payloadBytes: payloadBytes,
        kind: kind == 0 ? SampleKind.put : SampleKind.delete,
        attachment: attachmentBytes != null
            ? utf8.decode(attachmentBytes, allowMalformed: true)
            : null,
        attachmentBytes: attachmentBytes,
        encoding: encoding,
      );
      controller.add(sample);
    }
  });

  return (receivePort, controller);
}