writeEventChannelApi method

  1. @override
void writeEventChannelApi(
  1. KotlinOptions 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(
  KotlinOptions generatorOptions,
  Root root,
  Indent indent,
  AstEventChannelApi api, {
  required String dartPackageName,
}) {
  indent.newln();
  indent.format('''
      private class PigeonStreamHandler<T>(
          val wrapper: PigeonEventChannelWrapper<T>
      ) : EventChannel.StreamHandler {
        var pigeonSink: PigeonEventSink<T>? = null

        override fun onListen(p0: Any?, sink: EventChannel.EventSink) {
          pigeonSink = PigeonEventSink<T>(sink)
          wrapper.onListen(p0, pigeonSink!!)
        }

        override fun onCancel(p0: Any?) {
          pigeonSink = null
          wrapper.onCancel(p0)
        }
      }

      interface PigeonEventChannelWrapper<T> {
        open fun onListen(p0: Any?, sink: PigeonEventSink<T>) {}

        open fun onCancel(p0: Any?) {}
      }

      class PigeonEventSink<T>(private val sink: EventChannel.EventSink) {
        fun success(value: T) {
          sink.success(value)
        }

        fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
          sink.error(errorCode, errorMessage, errorDetails)
        }

        fun endOfStream() {
          sink.endOfStream()
        }
      }
    ''');
  addDocumentationComments(
      indent, api.documentationComments, _docCommentSpec);
  for (final Method func in api.methods) {
    indent.format('''
      abstract class ${toUpperCamelCase(func.name)}StreamHandler : PigeonEventChannelWrapper<${_kotlinTypeForDartType(func.returnType)}> {
        companion object {
          fun register(messenger: BinaryMessenger, streamHandler: ${toUpperCamelCase(func.name)}StreamHandler, instanceName: String = "") {
            var channelName: String = "${makeChannelName(api, func, dartPackageName)}"
            if (instanceName.isNotEmpty()) {
              channelName += ".\$instanceName"
            }
            val internalStreamHandler = PigeonStreamHandler<${_kotlinTypeForDartType(func.returnType)}>(streamHandler)
            EventChannel(messenger, channelName, ${generatorOptions.fileSpecificClassNameComponent}$_pigeonMethodChannelCodec).setStreamHandler(internalStreamHandler)
          }
        }
      }
    ''');
  }
}