Created
July 22, 2012 19:06
-
-
Save juliangruber/3160726 to your computer and use it in GitHub Desktop.
Pubsub in Dart
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 Pubsub { | |
Map channels; | |
Pubsub() { | |
channels = new Map(); | |
} | |
subscribe(String channel, Function cb) { | |
if (channels[channel] == null) { | |
channels[channel] = new List<Function>(); | |
} | |
channels[channel].add(cb); | |
} | |
publish(String channel, var message) { | |
for (Function cb in channels[channel]) { | |
try { | |
cb(message); | |
} catch (final Exception e) { | |
print(e); | |
} | |
} | |
} | |
unsubscribe(String channel, Function fun) { | |
if (channels[channel] != null) { | |
int i = channels[channel].indexOf(fun); | |
if (i > -1) { | |
channels[channel].removeRange(i, 1); | |
} | |
} | |
} | |
} | |
void main() { | |
Pubsub pubsub = new Pubsub(); | |
void printMessage(var message) { | |
print(message); | |
} | |
pubsub.subscribe('123', printMessage); // subscribes on channel `123` | |
pubsub.publish('123', 'a message'); // prints out `a message` | |
pubsub.unsubscribe('123', printMessage); // unsubscribes from channel `123` | |
pubsub.unsubscribe('1234', printMessage); // tries unsubscribing from channel `1234` | |
pubsub.publish('123', 'a second message'); // prints out nothing | |
pubsub.subscribe('123', printMessage); // subscribes again on channel `123` | |
pubsub.publish('123', 'a third message'); // prints out `a third message` | |
pubsub.publish('123', ['one', 'two']); // prints the array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I know this is a very old gist but I found it useful. I just updated the code to enable soundness. Here it is on DartPad, and I'm copypasting below.
Also worth mentioning that most modern Dart code would just use
Stream
for pubsub functionality (namely, broadcast streams).