processGenAIStreamOutput function
void
processGenAIStreamOutput()
Implementation
void processGenAIStreamOutput(
Stream<String?> stream,
Function(String) onWord,
Function(dynamic) onError,
) {
String buffer = '';
stream.listen(
(chunk) {
if (chunk == null || chunk.isEmpty) return;
buffer += chunk;
// Split on spaces but preserve last partial word
final parts = buffer.split(RegExp(r'\s+'));
if (parts.length > 1) {
// Keep the last part in buffer (it may be incomplete)
buffer = parts.removeLast();
for (final word in parts) {
if (word.trim().isNotEmpty) {
onWord(word);
}
}
}
},
onDone: () {
// Print any remaining word when stream is finished
if (buffer.trim().isNotEmpty) {
onWord(buffer);
}
},
onError: (e) {
onError(e);
},
);
}