getResponseAsync method

  1. @override
Stream<String?> getResponseAsync({
  1. required String prompt,
})
override

Implementation

@override
Stream<String?> getResponseAsync({required String prompt}) {
  if (_initCompleter.isCompleted) {
    final StreamController<String?> controller = StreamController<String?>();

    eventChannel.receiveBroadcastStream().listen(
          (event) {
        if (event is Map && event.containsKey('code') && event['code'] == "ERROR") {
          controller.addError(Exception(event['message'] ?? 'Unknown async error occurred'));
        } else {
          controller.add(event as String?);
        }
      },
      onError: (error) {
        controller.addError(Exception('Stream error: $error'));
      },
      onDone: controller.close,
    );

    methodChannel.invokeMethod('getGemmaResponseAsync', {'prompt': prompt}).catchError((error) {
      if (error is PlatformException) {
        controller.addError(Exception('Platform error: ${error.message}'));
      } else {
        controller.addError(Exception('Unknown invoke error: $error'));
      }
    });

    return controller.stream;
  } else {
    throw Exception('Gemma is not initialized yet');
  }
}