Skip to content

Instantly share code, notes, and snippets.

@christianalfoni
Created April 3, 2019 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianalfoni/9ce534df66922cd7d43fbfdbb0368f74 to your computer and use it in GitHub Desktop.
Save christianalfoni/9ce534df66922cd7d43fbfdbb0368f74 to your computer and use it in GitHub Desktop.
class Store {
Store([Store parent = null]) {
this.emit = parent == null ? (dynamic action) {
if (_subscribers.containsKey(action)) {
_subscribers[action].forEach((cb) => cb());
}
} : parent.emit;
}
Map<Action, Set<Function>> _subscribers = new Map();
Function subscribe(List<Action> actions, Function callback) {
actions.forEach((action) {
_subscribers.putIfAbsent(action, () => new Set());
_subscribers[action].add(callback);
});
return () {
actions.forEach((action) {
_subscribers[action].remove(callback);
});
};
}
void Function(dynamic action) emit;
}
enum Action {
ChangeCount,
ChangeFoo
}
class OtherStore extends Store {
OtherStore(Store parent) : super(parent);
String foo = "bar";
void changeFoo() {
foo += "!!!";
emit(Action.ChangeFoo);
}
}
class MyStore extends Store {
OtherStore other;
MyStore() {
this.other = new OtherStore(this);
}
int count = 0;
void changeCount() {
++count;
emit(Action.ChangeCount);
}
}
void main() {
final store = MyStore();
store.subscribe([Action.ChangeCount, Action.ChangeFoo], () {
print("hey!");
});
store.changeCount();
store.other.changeFoo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment