postStreamRaw method

Stream<String> postStreamRaw(
  1. String endpoint,
  2. Map<String, dynamic> data
)

Make a POST request and return raw stream for SSE

Implementation

Stream<String> postStreamRaw(
  String endpoint,
  Map<String, dynamic> data,
) async* {
  try {
    final response = await dio.post(
      endpoint,
      data: data,
      options: Options(
        responseType: ResponseType.stream,
        headers: {'Accept': 'text/event-stream'},
      ),
    );

    // Handle ResponseBody properly for streaming
    final responseBody = response.data;
    Stream<List<int>> stream;

    if (responseBody is Stream<List<int>>) {
      stream = responseBody;
    } else if (responseBody is ResponseBody) {
      stream = responseBody.stream;
    } else {
      throw Exception(
          'Unexpected response type: ${responseBody.runtimeType}');
    }

    // Use UTF-8 stream decoder to handle incomplete byte sequences
    final decoder = Utf8StreamDecoder();

    await for (final chunk in stream) {
      final decoded = decoder.decode(chunk);
      if (decoded.isNotEmpty) {
        yield decoded;
      }
    }

    // Flush any remaining bytes
    final remaining = decoder.flush();
    if (remaining.isNotEmpty) {
      yield remaining;
    }
  } on DioException catch (e) {
    logger.severe('Stream request failed: ${e.message}');
    rethrow;
  }
}