runStreamWithCallback method

Future<void> runStreamWithCallback({
  1. required TuulOptions tuulOptions,
  2. required void onEvent(
    1. SseEvent event
    ),
  3. void onDone()?,
  4. void onError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
})

Initiates a streaming request using Server-Sent Events (SSE) and callbacks.

This is ideal for Flutter UIs where you want to update the state as tokens arrive via onEvent.

  • tuulOptions: Configuration for the generation.
  • onEvent: Called whenever a new SseEvent (like a token) is received.
  • onDone: Called when the stream closes normally.
  • onError: Called if the connection or parsing fails.

Implementation

Future<void> runStreamWithCallback({
  required TuulOptions tuulOptions,
  required void Function(SseEvent event) onEvent,
  void Function()? onDone,
  void Function(Object error, StackTrace stackTrace)? onError,
}) async {
  tuulOptions.validate();

  await client.sse(
    "/generate",
    method: 'POST',
    headers: _headers(),
    body: tuulOptions.toJson(),
    onChunk: (chunk) {
      try {
        final decoded = jsonDecode(chunk);

        if (decoded is Map<String, dynamic>) {
          onEvent(SseEvent.fromJson(decoded));
        }
      } catch (_) {
        // Ignore keep-alive / malformed chunks
      }
    },
    onDone: onDone,
    onError: onError,
  );
}