flutter_client_sse
flutter_client_sse copied to clipboard
onDone callback not working when connection closes
Hello there,
I have been using this library and it worked fine but I have one problem with it: when the server closes the connection (Which I have checked is done right and works on postman for example), I cannot figure out how to detect it.
So I have made a EventStreamManager class that handles the stream because I needed a broadcast stream (then I figured out I could maybe do it simpler but that's not the point).
I can get events and all but nothing ever passes in the onDone callback function. I have tried everything but I cannot figure out how to make it work.
Has someone ever made it work ?
EventStreamManager.dart
import 'dart:async';
import 'package:echo_app/api/api_client.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_client_sse/flutter_client_sse.dart';
class EventStreamManager {
final ApiClient _apiClient;
StreamController<SSEModel>? _streamController;
EventStreamManager(this._apiClient);
Stream<SSEModel> get stream => _streamController!.stream;
Future<void> startListeningForEvents(String sessionId) async {
_streamController = StreamController<SSEModel>.broadcast();
Stream<SSEModel> eventStream =
await _apiClient.startListeningForEvents(sessionId);
eventStream.listen((event) {
if (!_streamController!.isClosed) {
_streamController!.sink.add(event);
}
}, onDone: () {
if (kDebugMode) {
print('SSE closed');
}
_streamController!.close();
}, onError: (error) {
_streamController!.addError(error);
});
}
void stopListeningForEvents() {
_apiClient.stopListeningForEvents();
_streamController?.close();
_streamController = null;
}
}
ApiClient.startListeningForEvents function:
Future<Stream<SSEModel>> startListeningForEvents(String sessionId) async {
var token = await getAccessToken();
return SSEClient.subscribeToSSE(
method: SSERequestType.GET,
url: '$baseUrl/sessions/$sessionId',
header: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
});
}