Created
April 3, 2019 14:17
-
-
Save christianalfoni/9ce534df66922cd7d43fbfdbb0368f74 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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