File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed
patterns/observer/app_observer Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change 1+ import 'observer/app_observer.dart' ;
2+ import 'observer/event.dart' ;
3+
4+ class FirstEvent extends Event {}
5+
6+ class SecondEvent extends Event {}
7+
8+ class ThirdEvent extends Event {}
9+
10+ void main () {
11+ final observer = AppObserver ();
12+
13+ observer.subscribe <FirstEvent >((e) {
14+ print ('First' );
15+ });
16+
17+
18+ observer.subscribe ((SecondEvent e) {
19+ print ('Second' );
20+ });
21+
22+ final saveThirdEvent = observer.subscribe ((ThirdEvent e) {
23+ print ('Third' );
24+ });
25+
26+ observer.notify (FirstEvent ());
27+ observer.notify (SecondEvent ());
28+ observer.notify (ThirdEvent ());
29+
30+ print ('---unsubscribe "ThirdEvent"---' );
31+ observer.unsubscribe (saveThirdEvent);
32+
33+ observer.notify (FirstEvent ());
34+ observer.notify (SecondEvent ());
35+ observer.notify (ThirdEvent ());
36+ }
Original file line number Diff line number Diff line change 1+ import 'event.dart' ;
2+
3+ typedef EventFunction <T > = void Function (T e);
4+
5+ class AppObserver {
6+ final _subscribers = < int , List <dynamic >> {};
7+
8+ EventFunction <T > subscribe <T >(EventFunction <T > func) {
9+ assert (
10+ Class <T >() is Class <Event >,
11+ '\n\n The callback argument must implement the "Event" class.\n '
12+ 'Correct use: \n '
13+ '\t observer.subscribe((MyEvent e) {}); \n '
14+ 'Mistaken usage: \n '
15+ '\t observer.subscribe((String e) {});\n '
16+ '\t observer.subscribe((e) {});\n ' ,
17+ );
18+
19+ _subscribers.putIfAbsent (T .hashCode, () => []).add (func);
20+ return func;
21+ }
22+
23+ void unsubscribe <T extends Event >(EventFunction <T > func) {
24+ final isDelete = _subscribers[T .hashCode]? .remove (func) ?? false ;
25+
26+ if (isDelete) {
27+ return ;
28+ }
29+
30+ throw Exception ('Subscriber not found.' );
31+ }
32+
33+ void notify <T extends Event >(T event) {
34+ final subscribers = _subscribers[T .hashCode];
35+
36+ if (subscribers == null ) {
37+ return ;
38+ }
39+
40+ for (var sub in subscribers) {
41+ sub.call (event);
42+ }
43+ }
44+ }
45+
46+ class Class <T > {}
Original file line number Diff line number Diff line change 1+ abstract class Event {
2+
3+ }
You can’t perform that action at this time.
0 commit comments