Hi,
I found the following methods are quite useful to control stream.
Currently, I create an extension on StreamController, is it possible to add these methods in StreamController?
void mayAdd(T event) {
if (!isClosed && hasListener) {
add(event);
}
}
void mayAddError(Object error, [StackTrace? stackTrace]){
if (!isClosed && hasListener) {
addError(error, stackTrace);
}
}
Future<void> mayClose() async {
if (!isClosed && !hasListener) {
await close();
}
}
If the
onCancel
is on the stream ofcontroller
, then I can absolutely gurantee thatcontroller.hasListener
will be false whenonCancel
is called, both for single-subscription and broadcast streams. Not having a listener is what triggersonCancel
being called.What you do is equivalent to
await controller?.close()
. It’s safe to call close twice, so there is no need to checkisClosed
first.If it is not a broadcast stream, it’s unnecessary to close the controller. The one and only listener has already stopped listening, so noone will get the
done
event.For the remaining uses, I think they derive from the way you are using controllers, but they are not general enough that we’d want to have them on the controller for everybody.