Commit | Line | Data |
31a246e4 |
1 | package Tak::Loop; |
2 | |
77bf1d9b |
3 | use IO::Select; |
31a246e4 |
4 | use Moo; |
5 | |
77bf1d9b |
6 | has is_running => (is => 'rw', clearer => 'loop_stop'); |
7 | |
8 | has _read_watches => (is => 'ro', default => sub { {} }); |
9 | has _read_select => (is => 'ro', default => sub { IO::Select->new }); |
10 | |
11 | sub watch_io { |
12 | my ($self, %watch) = @_; |
13 | my $fh = $watch{handle}; |
14 | if (my $cb = $watch{on_read_ready}) { |
15 | $self->_read_select->add($fh); |
16 | $self->_read_watches->{$fh} = $cb; |
17 | } |
18 | } |
19 | |
20 | sub unwatch_io { |
21 | my ($self, %watch) = @_; |
22 | my $fh = $watch{handle}; |
23 | if ($watch{on_read_ready}) { |
24 | $self->_read_select->remove($fh); |
25 | delete $self->_read_watches->{$fh}; |
26 | } |
27 | } |
28 | |
29 | sub loop_once { |
30 | my ($self) = @_; |
31 | my $read = $self->_read_watches; |
32 | my ($readable) = IO::Select->select($self->_read_select); |
33 | foreach my $fh (@$readable) { |
34 | $read->{$fh}(); |
35 | } |
36 | } |
37 | |
38 | sub loop_forever { |
39 | my ($self) = @_; |
40 | $self->is_running(1); |
41 | while ($self->is_running) { |
42 | $self->loop_once; |
43 | } |
44 | } |
45 | |
31a246e4 |
46 | 1; |