Skip to content

Conversation

@ilopX
Copy link
Collaborator

@ilopX ilopX commented Feb 1, 2022

Important

This pull request includes a commit with an initial flutter launcher for online demos that will be used later.

Observer pattern

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify
multiple objects about any events that happen to the object they’re observing.

Tutorial: here.

AppObserver example

This example was created to be used in a more complex example.
A complex example will be implemented later.

Diagram:

image

Sequence

image

Client code:

void main() {
  final observer = AppObserver();

  observer.subscribe<FirstEvent>((e) {
    print('First');
  });


  observer.subscribe((SecondEvent e) {
    print('Second');
  });

  final saveThirdEvent = observer.subscribe((ThirdEvent e) {
    print('Third');
  });

  observer.notify(FirstEvent());
  observer.notify(SecondEvent());
  observer.notify(ThirdEvent());

  print('---unsubscribe "ThirdEvent"---');
  observer.unsubscribe(saveThirdEvent);

  observer.notify(FirstEvent());
  observer.notify(SecondEvent());
  observer.notify(ThirdEvent());
}

Output:

First
Second
Third
---unsubscribe "ThirdEvent"---
First
Second

@neochief neochief merged commit 8d1ebf5 into RefactoringGuru:master Feb 2, 2022
@neochief
Copy link
Contributor

neochief commented Feb 2, 2022

Thanks a lot!

@ilopX ilopX deleted the add-observer-example-for-further-use-in-more-complex-examples branch February 2, 2022 19:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants