close method
Implementation
@override
Future<void> close() async {
// Idempotent: a second close must not run native `closeSession()`
// again. With the singleton-session lifecycle (a fresh createSession
// supersedes the prior wrapper), a superseded wrapper and the live
// one can both be closed by a caller; without this guard the stale
// close would tear down the *current* native session (closeSession
// is argument-less and closes whatever session is active). See the
// createSession comment and issue #308.
if (_isClosed) return;
_isClosed = true;
// Cancel event subscription first to stop receiving events
await _eventSubscription?.cancel();
_eventSubscription = null;
// Try to stop generation if possible (ignore errors on unsupported platforms)
try {
await _platformService.stopGeneration();
} on PlatformException catch (e) {
// Ignore "not supported" errors, but rethrow others
if (e.code != 'stop_not_supported') {
if (kDebugMode) {
gemmaLog('Warning: Failed to stop generation: ${e.message}');
}
}
} catch (e) {
// Ignore other errors during cleanup
if (kDebugMode) {
gemmaLog('Warning: Unexpected error during stop generation: $e');
}
}
// Close controller after stopping subscription
_asyncResponseController?.close();
onClose();
await _platformService.closeSession();
}