Skip to content

Instantly share code, notes, and snippets.

/PubSub.pm Secret

Created February 14, 2015 02:34
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 anonymous/bee1317bfd6e6925dbea to your computer and use it in GitHub Desktop.
Save anonymous/bee1317bfd6e6925dbea to your computer and use it in GitHub Desktop.
package Mojo::Pg::PubSub;
use Mojo::Base 'Mojo::EventEmitter';
use Scalar::Util 'weaken';
has 'pg';
sub listen {
my ($self, $name, $cb) = @_;
push @{$self->{chans}{$name}}, $cb;
$self->_db->listen($name) unless @{$self->{chans}{$name}} > 1;
return $cb;
}
sub notify { $_[0]->_db->notify(@_[1, 2]) and return $_[0] }
sub unlisten {
my ($self, $name, $cb) = @_;
my $chans = $self->{chans}{$name};
@$chans = grep { $cb ne $_ } @$chans;
$self->_db->unlisten($name) and delete $self->{chans}{$name} unless @$chans;
return $self;
}
sub _db {
my $self = shift;
return $self->{db} if $self->{db};
$self->emit(reconnect => my $db = $self->{db} = $self->pg->db);
weaken $self;
$db->on(
notification => sub {
my ($db, $name, $pid, $payload) = @_;
for my $cb (@{$self->{chans}{$name}}) { $self->$cb($payload) }
}
);
$db->once(
close => sub {
delete $self->{db};
my $db = $self->_db;
$db->listen($_) for keys %{$self->{chans}};
}
);
return $db;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment