Skip to content

Commit 0b80057

Browse files
committed
Add README.
1 parent 9f970a2 commit 0b80057

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Observer pattern
2+
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify
3+
multiple objects about any events that happen to the object they’re observing.
4+
5+
Tutorial: [here](https://refactoring.guru/design-patterns/observer).
6+
7+
## AppObserver example
8+
This example was created to be used in a more complex example.
9+
A complex example will be implemented later.
10+
11+
### Diagram:
12+
![image](https://user-images.githubusercontent.com/8049534/152049751-b111e02a-1d33-4796-810c-b7ed069cecdc.png)
13+
14+
### Sequence
15+
![image](https://user-images.githubusercontent.com/8049534/152049996-72131655-402d-4b92-b5d0-10e3f2dd0e79.png)
16+
17+
### Client code:
18+
```dart
19+
void main() {
20+
final observer = AppObserver();
21+
22+
observer.subscribe<FirstEvent>((e) {
23+
print('First');
24+
});
25+
26+
27+
observer.subscribe((SecondEvent e) {
28+
print('Second');
29+
});
30+
31+
final saveThirdEvent = observer.subscribe((ThirdEvent e) {
32+
print('Third');
33+
});
34+
35+
observer.notify(FirstEvent());
36+
observer.notify(SecondEvent());
37+
observer.notify(ThirdEvent());
38+
39+
print('---unsubscribe "ThirdEvent"---');
40+
observer.unsubscribe(saveThirdEvent);
41+
42+
observer.notify(FirstEvent());
43+
observer.notify(SecondEvent());
44+
observer.notify(ThirdEvent());
45+
}
46+
```
47+
48+
**Output:**
49+
```
50+
First
51+
Second
52+
Third
53+
---unsubscribe "ThirdEvent"---
54+
First
55+
Second
56+
```

0 commit comments

Comments
 (0)