Reactiveってなに?って方は Reactive とは何か? を読んでください。
この記事ではちょっとずつ加筆修正しながらReactive Programmingを試していきたいと思います。
一緒に勉強して下さる方とかいたら Twitter::PitneS まで連絡下さるとうれしーです。
1. Ping, Pong
emit
参考資料2では次のようなソースがExample Codeとして記載されています。
package Echoer;
use Moose;
extends 'Reflex::Base';
sub ping {
my ($self, $args) = @_;
print "echoer was pinged!\n";
$self->emit( -name => "pong" );
}
Mooseは、完全なオブジェクトシステムをPerl5に提供するライブラリです。Mooseで使用されるAttributesはこちらで参照できます。
一例を挙げると、例えば型はVar is a Str
のようにisa
を用いて定義され、属性はVar is read-only
のようにis
を用いて設定されます。
また、extends
はよくあるオブジェクトの継承に利用される関数です。Mooseをuseしているので使えています。
package User;
use Moose;
extends 'Person';
has 'password' => (
is => 'rw',
isa => 'Str',
);
Example CodeによるとEchoerはping関数を持ち、そこでは Reflex::Role::Reactive
で定義されるemit関数が使われています。
emitとは何か。ここによれば、watch() allows one object (the watcher) to register interest in events emitted by another.
とあり、watcherによって観測されるeventの一種だということが分かります。
react
ところでPinger側のExample Codeでは、型がEchoer
のデフォルト値sub { Echoer->new() }
の読み書き可能な(has
ではなくwatches
を用いているため)echoerを宣言しています。
package Pinger;
use Moose;
extends 'Reflex::Base';
use Reflex::Trait::Watched qw(watches);
watches echoer => (
isa => 'Echoer',
default => sub { Echoer->new() },
);
sub BUILD {
my $self = shift;
$self->echoer->ping;
}
sub on_echoer_pong {
my $self = shift;
print "Pinger got echoer's pong!\n";
$self->echoer->ping();
}
宣言されたechoerはPingerのBUILD時に呼ばれ、結果としてpingが実行されます。
その場合、冒頭でも記したようにpingはpongをemitするため、Pingerのon_(オブジェクト名)_(当該オブジェクトがemitしたイベント名) { ... }
が呼び出されることになります。
結果として、
PitneS$ perl -e "use Pinger; use Echoer; Pinger->new()->run_all();"
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
Pinger got echoer's pong!
echoer was pinged!
...
という結果が得られます。なお run_all();
はこちらによれば run_all(): Run all active Reflex objects until they destruct.
、つまり生成したReflexオブジェクトを実行する関数です。
参考資料
URL
- Reactive とは何か? 18Aug2015, by @okapies.
- Reflex - Class library for flexible, reactive programs. 21Apr2013, by Rocco Caputo.
- Moose - A postmodern object system for Perl 5 2006, by Infinity Interactive, Inc.
- Moose::Manual - Mooseとはなにか、どうやって使うのか 2008-2009 by Infinity Interactive, Inc.