Created
November 17, 2012 02:31
-
-
Save kentfredric/4092780 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
use strict; | |
use warnings; | |
use IO::Async::Channel; | |
use IO::Async::Loop; | |
use IO::Async::Routine; | |
my $loop = IO::Async::Loop->new(); | |
{ | |
package Slave; | |
use parent 'IO::Async::Routine'; | |
sub configure { | |
my $self = shift; | |
my %params = @_; | |
$self->{controlstream} = IO::Async::Channel->new( | |
on_recv => sub { | |
my ( $channel, $data ) = @_; | |
my $event = delete $data->{event}; | |
if ( exists $self->{events}->{$event} ) { | |
return $self->{events}->{$event}->($data); | |
} | |
warn "Unhanlded event << $event >>\n"; | |
} | |
); | |
$self->{loop_setup} = delete $params{loop_setup}; | |
$self->{events} = delete $params{events}; | |
$self->{events} //= {}; | |
$self->SUPER::configure( | |
%params, | |
channels_in => [ $self->{controlstream} ], | |
channels_out => [], | |
code => sub { | |
$self->run(); | |
}, | |
); | |
} | |
sub _add_to_loop { | |
my $self = shift; | |
if ( exists $self->{loop_setup} ) { | |
$self->{loop_setup}->( $self, @_ ); | |
} | |
$self->SUPER::_add_to_loop(@_); | |
} | |
sub do_event { | |
my ( $self, $event, @args ) = @_; | |
my $message = { | |
event => $event, | |
args => \@args | |
}; | |
$self->{controlstream}->send($message); | |
} | |
sub on_finish { | |
warn "Got exit condition before the exit signal\n"; | |
$loop->stop(); | |
} | |
} | |
my $slave = Slave->new( | |
setup => sub { | |
my ( $self, $loop ) = @_; | |
}, | |
events => { | |
'hello' => sub { STDERR->say("Got HELLO in slave"); }, | |
'exit' => sub { STDERR->say("Got EXIT in slave"); }, | |
}, | |
); | |
$loop->add($slave); | |
$slave->do_event( hello => {} ); | |
$slave->do_event( exit => {} ); | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment