Reputation: 199
I'm having this problem closing streams: bad state: cannot add new events after calling close
In dispose I call the controller's close method, but when I go to a new screen of my application and go back before the data is loaded that error is generated, I have seen that the controller's drain method can be done, but then The close method is not executed, that is, it is waiting for the future to finish.
Using the drain method no longer shows the error, but I don't know if it is the right thing to close a stream.
import 'dart:async';
import 'package:rxdart/rxdart.dart';
class PersonBloc {
final BehaviorSubject<String> _nameController = BehaviorSubject<String>();
Function(String) get nameSink => _nameController.sink.add;
Stream<String> get nameStream => _nameController.stream;
final BehaviorSubject<String> _cityController = BehaviorSubject<String>();
Function(String) get nameSink => _cityController.sink.add;
Stream<String> get nameStream => _cityController.stream;
Future<void> dispose() async {
_nameController?.close();
_cityController?.close();
}
Future<void> dispose2() async {
await _nameController.drain();
_nameController?.close();
await _cityController?.drain();
_cityController?.close();
}
}
I don't know if it is correct to use a condition to check if the stream is closed and thus avoid this error.
if(!_nameController.isClosed){
nameSink("Maria")
...
}
Upvotes: 0
Views: 1649
Reputation: 10519
A Stream can be only be listened to once. If you try to add a listener after closing the Stream, it will throw a Bad state
error.
Dispose should be called when the screen using the Stream has been disposed. So if you're adding a new event to the Stream on the same Screen that hasn't been disposed, it'll throw the same error. As a workaround, since closed Streams can't be reopened, you can reinitialize the Stream after closing it.
Upvotes: 0