Unsuscribe every handler of an event Unsuscribe every handler of an event dart dart

Unsuscribe every handler of an event


Use a decorator pattern:

class MyStream<T> implements Stream<T>{    Stream<T> _stream;    List<StreamSubscription<T>> _subs;    /*       use noSuchMethod to pass all calls directly to _stream,       and simply override the call to listen, and add a new method to removeAllListeners    */    StreamSubscription<T> listen(handler){       var sub = _stream.listen(handler);       _subs.add(sub);       return sub;    }    void removeAllListeners(){       _subs.forEach((s) => s.cancel());       _subs.clear();    }}

if you wanted to use this on html elements you could do exactly the same decorator pattern on a MyElement by decorating Element. Example:

class MyElement implements Element{    Element _element;    /*        use noSuchMethod to pass all calls directly to _element and simply override        the event streams you want to be able to removeAllListeners from    */    MyElement(Element element){        _element = element;        _onClick = new MyStream<MouseEvent>(_element.onClick);    }    MyStream<MouseEvent> _onClick;    MyStream<MouseEvent> get onClick => _onClick; //override the original stream getter here :)}

Then use accordingly:

var superDivElement = new MyElement(new DivElement());superDivElement.onClick.listen(handler);//...superDivElement.onClick.removeAllListeners();


You have to store the reference to be able to cancel the event.