writeEventChannelApi method

  1. @override
void writeEventChannelApi(
  1. SwiftOptions generatorOptions,
  2. Root root,
  3. Indent indent,
  4. AstEventChannelApi api, {
  5. required String dartPackageName,
})
override

Writes a single event channel Api to indent.

Implementation

@override
void writeEventChannelApi(
  SwiftOptions generatorOptions,
  Root root,
  Indent indent,
  AstEventChannelApi api, {
  required String dartPackageName,
}) {
  indent.newln();
  indent.format('''
    private class PigeonStreamHandler<ReturnType>: NSObject, FlutterStreamHandler {
      private let wrapper: PigeonEventChannelWrapper<ReturnType>
      private var pigeonSink: PigeonEventSink<ReturnType>? = nil

      init(wrapper: PigeonEventChannelWrapper<ReturnType>) {
        self.wrapper = wrapper
      }

      func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink)
        -> FlutterError?
      {
        pigeonSink = PigeonEventSink<ReturnType>(events)
        wrapper.onListen(withArguments: arguments, sink: pigeonSink!)
        return nil
      }

      func onCancel(withArguments arguments: Any?) -> FlutterError? {
        pigeonSink = nil
        wrapper.onCancel(withArguments: arguments)
        return nil
      }
    }

    class PigeonEventChannelWrapper<ReturnType> {
      func onListen(withArguments arguments: Any?, sink: PigeonEventSink<ReturnType>) {}
      func onCancel(withArguments arguments: Any?) {}
    }

    class PigeonEventSink<ReturnType> {
      private let sink: FlutterEventSink

      init(_ sink: @escaping FlutterEventSink) {
        self.sink = sink
      }

      func success(_ value: ReturnType) {
        sink(value)
      }

      func error(code: String, message: String?, details: Any?) {
        sink(FlutterError(code: code, message: message, details: details))
      }

      func endOfStream() {
        sink(FlutterEndOfEventStream)
      }

    }
    ''');
  addDocumentationComments(
      indent, api.documentationComments, _docCommentSpec);
  for (final Method func in api.methods) {
    indent.format('''
      class ${toUpperCamelCase(func.name)}StreamHandler: PigeonEventChannelWrapper<${_swiftTypeForDartType(func.returnType)}> {
        static func register(with messenger: FlutterBinaryMessenger,
                            instanceName: String = "",
                            streamHandler: ${toUpperCamelCase(func.name)}StreamHandler) {
          var channelName = "${makeChannelName(api, func, dartPackageName)}"
          if !instanceName.isEmpty {
            channelName += ".\\(instanceName)"
          }
          let internalStreamHandler = PigeonStreamHandler<${_swiftTypeForDartType(func.returnType)}>(wrapper: streamHandler)
          let channel = FlutterEventChannel(name: channelName, binaryMessenger: messenger, codec: ${_getMethodCodecVarName(generatorOptions)})
          channel.setStreamHandler(internalStreamHandler)
        }
      }
    ''');
  }
}