SlideShare a Scribd company logo
Reflex
How does it work?
   Rocco Caputo – @rcaputo
     Orlando Perl Workshop
    Saturday, 15 January 2011
         Around Noon
Reflex
 What Is It?
Rocco Caputo – @rcaputo
  Orlando Perl Workshop
 Saturday, 15 January 2011
      Around Noon
What’s Reflex?!


• Library of roles that process eventy stuff—
  timers, I/O notifications, signals, etc.
• Eventy class library built with those roles.
Reflex Roles–Briefly
package AsyncConsole;
use Moose; extends 'Reflex::Base';

has stdin => (
   is       => 'rw',
   isa      => 'FileHandle',
   required => 1,
);

with 'Reflex::Role::Readable' => {
   handle     => 'stdin',
   cb_ready   => 'get_keystroke',
};

sub get_keystroke { ... }
Reflex Roles?
package Console;
use Moose; extends 'Reflex::Base';

has stdout    =>   (
   is         =>   'rw',
   isa        =>   'FileHandle',
   required   =>   1,
);

with 'Reflex::Role::Readable' => {
   handle     => 'stdin',
   cb_ready   => 'get_keystroke',
};

sub get_keystroke { ... }
Except Much
   Better
I’ll Explain
at YAPC::NA
Reflex
How does it work?
   Rocco Caputo – @rcaputo
     Orlando Perl Workshop
    Saturday, 15 January 2011
         Around Noon
Magic
Sufficiently
 Advanced
Technology
“Sufficiently
Advanced”
     =
 We Don’t
 Know Yet
Learn
Magic in 90
 Minutes
Learn Just
Enough Magic in
 20 Minutes to
 Harm Yourself
Learn Just
Enough Magic in
 18 Minutes to
 Harm Yourself
Reflex
How does it work?
   Rocco Caputo – @rcaputo
     Orlando Perl Workshop
    Saturday, 15 January 2011
         Around Noon
Program
Composition
Dynamic Composition
• Objects are created,
 • related,
   • communicated (with),
     • and destructicated
       • at run time.
• Lather, rinse, repeat until the program ends.
Static Composition

• Code is bolted together before running.
• It stays that way “forever”.

• Subclassing.
• Moose roles.
Dynamic Reflex
Anonymous
 Callbacks
Ye Olde Coderef
use Reflex::Interval;

my $i = Reflex::Interval->new(
   interval => 1,
   on_tick => sub { print "tick...n" },
);

$i->run_all();
Ye Olde Coderef

tick...
tick...
tick...
^C
Ye Olde Coderef
• Quick and dead simple to use.
• Closure tricks for convenience and speed.

• Closures can’t use OO to extend or
  override event handlers.
• Uses circular references—memory leakage
  if you’re not careful.
Method
Callbacks
Methods
has ticker => (
  isa => 'Reflex::Interval', is => 'rw' );

sub BUILD {
  my $self = shift;
  $self->ticker(
     Reflex::Interval->new(
       interval => 1,
       on_tick => cb_method($self, "callback"),
     )
  );
}

sub callback { print "tick...n" }
Methods
has ticker => (
  isa => 'Reflex::Interval', is => 'rw' );

sub BUILD {
  my $self = shift;
  $self->ticker(
     Reflex::Interval->new(
       interval => 1,
       on_tick => cb_method($self, "callback"),
     )
  );
}

sub callback { print "tick...n" }
Methods
has ticker => (
  isa => 'Reflex::Interval', is => 'rw' );

sub BUILD {
  my $self = shift;
  $self->ticker(
     Reflex::Interval->new(
       interval => 1,
       on_tick => cb_method($self, "callback"),
     )
  );
}

sub callback { print "tick...n" }
Methods
• Cleaner object oriented design.
• Callbacks can use every Moose trick in the
  book.


• Requires more forethought.
• Perl & Moose OO less performant than
  anonymous subroutines & closures.
Observed
Attributes
Callbacks
 Discovered
Automatically
Moose
Traits Rock
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes clock => (
   isa    => 'Reflex::Interval',
   setup => sub {
      Reflex::Interval->new(interval => 1)
   },
);

sub on_clock_tick { print "tick...n" }
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes clock => (
   isa    => 'Reflex::Interval',
   setup => sub {
      Reflex::Interval->new(interval => 1)
   },
);

sub on_clock_tick { print "tick...n" }
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes clock => (
   isa    => 'Reflex::Interval',
   setup => sub {
      Reflex::Interval->new(interval => 1)
   },
);

sub on_clock_tick { print "tick...n" }
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes clock => (
   isa    => 'Reflex::Interval',
   setup => sub {
      Reflex::Interval->new(interval => 1)
   },
);

sub on_clock_tick { print "tick...n" }
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes clock => (
   isa    => 'Reflex::Interval',
   setup => sub {
      Reflex::Interval->new(interval => 1)
   },
);

sub on_clock_tick { print "tick...n" }
Observed Attributes
use Reflex::Trait::Observed qw(observes);

observes penguin => (
   isa   => 'Reflex::Bomb',
   setup => sub { ... },
);

sub on_penguin_tick { ... }
sub on_penguin_stop { ... }
sub on_penguin_explode { ... }
Observed Attributes

use Reflex::Trait::Observed qw(observes);

observes watchdog => ( ... Interval ... );
observes log_mark => ( ... Interval ... );

sub on_watchdog_tick { ... }
sub on_log_mark_tick { ... }
One Class,
Three Uses
“But callbacks
   suck!”
Promises
What’s a Promise?
“an object that acts as a proxy
for a result that is initially not
  known, usually because the
 computation of its value has
     not yet completed.”
         — Wikipedia
What’s a Promise?


Blah blah blah.
What’s a Promise?
• Asynchronous object.
 • Create it.
 • Do other stuff while it runs.
 • Pick up the result later.
• Blocks or returns “incomplete” if not done.
 • Other stuff runs while it blocks.
Timer Promise (1 of 2)
use Reflex::Interval;

my $one = Reflex::Interval->new(
   interval => 1
);

my $two = Reflex::Interval->new(
   interval => 2
);
Timer Promise (2 of 2)

print "Before   : ", time(), "n";

my $event = $two->next();
print "After two: ", time(), "n";

$event = $one->next();
print "After one: ", time(), "n";
Eventy Timer Promise

% perl this-time-for-sure.pl
Before   : 1295045065
After two: 1295045067
After one: 1295045067
Eventy Timer Promise

% perl this-time-for-sure.pl
Before   : 1295045065
After two: 1295045067
After one: 1295045067
One Class,
Three Four Uses
Four
Dynamic Uses
Static Reflex
Subclassing
Eventy Subclassing
{
    package MyTimer;
    use Moose;
    extends 'Reflex::Interval';

    before on_tick => sub { say "tick..." };
}

MyTimer->new( interval => 1 )->run_all();
Eventy Subclassing

tick...
tick...
tick...
^C
One Class
Four Five Uses
Must be a
beast, right?
Reflex::Interval (1 of 3)
package Reflex::Interval;
use Moose; extends 'Reflex::Base';

has interval => (
   isa => 'Num', is   => 'ro'
);

has auto_repeat => (
   isa => 'Bool', is => 'ro', default => 1
);

has auto_start => (
   isa => 'Bool', is => 'ro', default => 1
);
Reflex::Interval (2 of 3)
with 'Reflex::Role::Interval' => {
   interval      => "interval",
   auto_start    => "auto_start",
   auto_repeat   => "auto_repeat",
   cb_tick       => "on_tick",
   ev_tick       => "tick",
   method_start => "start",
   method_stop   => "stop",
   method_repeat => "repeat",
};
Reflex::Interval (3 of 3)



       1;
Roles
Reflex Roles
• Reflex eventiness implemented with roles.
 • Timers, I/O, signals, etc.
• Roles are reified by simple classes.
 • Reflex::Interval is Reflex::Role::Interval.
• Larger roles comprise simpler ones.
• It’s all Mooses, all the way down.
Parameterized Roles

• MooseX::Role::Parameterized rocks.
 • Parameters customize roles—fill in the
    blanks like templates.
 • Reflex uses it like breadboarding with
    Moose.
Lots of Role
Parameters
They’re Tedious
 to Configure
Smart Defaults

• A primary attribute identifies the role.
• Default parameters are named after that
  attribute.
• Roles avoid conflicts by default.
• Without tediously supplying all parameters.
Key Attribute
with 'Reflex::Role::Interval' => {
  interval => "watchdog",
}

Role Parameter          Default Name
  method_start         start_watchdog()

   method_stop          stop_watchdog()

     cb_tick          on_watchdog_tick()

     ev_tick             watchdog_tick
Key Attribute
with 'Reflex::Role::Interval' => {
  interval => "logmark",
}

Role Parameter          Default Name
  method_start          start_logmark()

   method_stop          stop_logmark()

     cb_tick           on_logmark_tick()

     ev_tick             logmark_tick
One Class
Role Five Six
    Uses
Dynamic Fun
Smalltalk Messaging
• Reflex::Trait::EmitsOnChange
• Emits an event when an attribute changes.
  use Reflex::Trait::EmitsOnChange qw(emits);

  emits count => (
     isa => 'Int', default => 0
  );

  sub on_ticker_tick {
    my $self = shift;
    $self->count($self->count() + 1);
  }
Smalltalk Messaging

use Reflex::Trait::EmitsOnChange qw(emits);

emits count => (
   isa => 'Int', default => 0
);

sub on_ticker_tick {
  my $self = shift;
  $self->count($self->count() + 1);
}
Reflex::Collection

• Manages Reflex::Role::Collectible objects.
• Removes them as they stop.
• Great for holding autonomous things.
Reflex::Collection
{
    package TcpEchoServer; use Moose;
    extends 'Reflex::Acceptor'; use EchoStream;
    use Reflex::Collection qw(has_many);

    has_many clients => (
      handles => { remember_client => "remember" } );

    sub on_accept {
      my ($self, $args) = @_;
      $self->remember_client(
         EchoStream->new( handle => $args->{socket} )
      );
    }
}
Reflex::Collection
{
    package TcpEchoServer; use Moose;
    extends 'Reflex::Acceptor'; use EchoStream;
    use Reflex::Collection qw(has_many);

    has_many clients => (
      handles => { remember_client => "remember" } );

    sub on_accept {
      my ($self, $args) = @_;
      $self->remember_client(
         EchoStream->new( handle => $args->{socket} )
      );
    }
}
Reflex::Collection
{
    package TcpEchoServer; use Moose;
    extends 'Reflex::Acceptor'; use EchoStream;
    use Reflex::Collection qw(has_many);

    has_many clients => (
      handles => { remember_client => "remember" } );

    sub on_accept {
      my ($self, $args) = @_;
      $self->remember_client(
         EchoStream->new( handle => $args->{socket} )
      );
    }
}
EchoStream
package EchoStream;
use Moose;
extends 'Reflex::Stream';

sub on_data {
  my ($self, $args) = @_;
  $self->put($args->{data});
}

1;
But is Reflex
   ready?
Reflex is Newish

• Large swathes of design are stable.
• Details need to be ironed out.
• Will happen faster if you use it.
• Help me find the edge cases.
How To Help
• http://github.com/rcaputo/reflex
 • See docs/TODO.otl
• #reflex on irc.perl.org
• poe-subscribe@perl.org
• Hackathon?
• Hire someone to use it on your project.
Contribute to a Project
• Nick Perez’s Reflex-based psgi server.
• Reflexive::Stream::Filtering
 • Attach POE filters to Reflex streams.
• Reflexive::Role::TCPServer
 • Consumable full-featured TCP server.
• (Your Project Here)
Thank you!

More Related Content

PPT
Mastering Java ByteCode
KEY
Djangocon11: Monkeying around at New Relic
ODP
ES6 PPT FOR 2016
PPTX
Mastering Java Bytecode With ASM - 33rd degree, 2012
PDF
LetSwift RxSwift 시작하기
PDF
Rust ⇋ JavaScript
PPTX
Using Reflections and Automatic Code Generation
PDF
Building fast interpreters in Rust
Mastering Java ByteCode
Djangocon11: Monkeying around at New Relic
ES6 PPT FOR 2016
Mastering Java Bytecode With ASM - 33rd degree, 2012
LetSwift RxSwift 시작하기
Rust ⇋ JavaScript
Using Reflections and Automatic Code Generation
Building fast interpreters in Rust

What's hot (20)

PDF
Explaining ES6: JavaScript History and What is to Come
PDF
ES6 - Next Generation Javascript
KEY
連邦の白いヤツ 「Objective-C」
PDF
PPTX
Ian 20150116 java script oop
PDF
Proxies are Awesome!
PPTX
Introduction to Ecmascript - ES6
KEY
Say Hello To Ecmascript 5
PPTX
ES6 in Real Life
PPTX
Akka in-action
PDF
Functions, Types, Programs and Effects
PDF
ES2015 (ES6) Overview
PDF
Your code is not a string
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PDF
Reactive Summit 2017
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
PDF
Javascript: the important bits
PDF
Think Async: Asynchronous Patterns in NodeJS
PDF
Execution model and other must-know's
PPTX
AST - the only true tool for building JavaScript
Explaining ES6: JavaScript History and What is to Come
ES6 - Next Generation Javascript
連邦の白いヤツ 「Objective-C」
Ian 20150116 java script oop
Proxies are Awesome!
Introduction to Ecmascript - ES6
Say Hello To Ecmascript 5
ES6 in Real Life
Akka in-action
Functions, Types, Programs and Effects
ES2015 (ES6) Overview
Your code is not a string
Functional Reactive Programming (FRP): Working with RxJS
Reactive Summit 2017
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Javascript: the important bits
Think Async: Asynchronous Patterns in NodeJS
Execution model and other must-know's
AST - the only true tool for building JavaScript
Ad

Viewers also liked (6)

PPTX
reflexes, clasifications, and functions.
PDF
Classification of reflexes
PPT
Reflexes, nervous system ppt
PPTX
Reflexes
PPTX
Reflex
PPSX
The Nervous System (Slide Show)
reflexes, clasifications, and functions.
Classification of reflexes
Reflexes, nervous system ppt
Reflexes
Reflex
The Nervous System (Slide Show)
Ad

Similar to Reflex - How does it work? (20)

PDF
Reflex - How Does It Work? (extended dance remix)
PDF
Reactive x
PDF
Asynchronous Programming FTW! 2 (with AnyEvent)
KEY
Concurrent programming with Celluloid (MWRC 2012)
PDF
CoffeeScript
KEY
Gevent what's the point
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
PPTX
Java script advance-auroskills (2)
PDF
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
PDF
rx.js make async programming simpler
PDF
Ruby basics
PDF
Introduction to Protractor
PPTX
Node.js System: The Landing
PPTX
Neuroevolution in Elixir
PDF
Any event intro
PDF
Coding in Style
PDF
Rxjs kyivjs 2015
PDF
Node.js Event Loop & EventEmitter
PPTX
Async Redux Actions With RxJS - React Rally 2016
PDF
The Ring programming language version 1.8 book - Part 88 of 202
Reflex - How Does It Work? (extended dance remix)
Reactive x
Asynchronous Programming FTW! 2 (with AnyEvent)
Concurrent programming with Celluloid (MWRC 2012)
CoffeeScript
Gevent what's the point
The Evolution of Async-Programming (SD 2.0, JavaScript)
Java script advance-auroskills (2)
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
rx.js make async programming simpler
Ruby basics
Introduction to Protractor
Node.js System: The Landing
Neuroevolution in Elixir
Any event intro
Coding in Style
Rxjs kyivjs 2015
Node.js Event Loop & EventEmitter
Async Redux Actions With RxJS - React Rally 2016
The Ring programming language version 1.8 book - Part 88 of 202

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
KodekX | Application Modernization Development
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Empathic Computing: Creating Shared Understanding
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Cloud computing and distributed systems.
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Big Data Technologies - Introduction.pptx
Approach and Philosophy of On baking technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
KodekX | Application Modernization Development
Programs and apps: productivity, graphics, security and other tools
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reach Out and Touch Someone: Haptics and Empathic Computing
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
Cloud computing and distributed systems.
sap open course for s4hana steps from ECC to s4
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced methodologies resolving dimensionality complications for autism neur...
Agricultural_Statistics_at_a_Glance_2022_0.pdf

Reflex - How does it work?

Editor's Notes