NAME

Method::WeakCallback - Call back object methods through weak references.

SYNOPSIS

package Foo::Bar;
use Method::WeakCallback qw(weak_method_callback);

use AE;

sub new { ... }

sub set_timer {
  my $obj = shift;
  $obj->{timer} = AE::timer(60, 60,
                      weak_method_callback($obj, 'on_timeout'));
}

sub on_timeout { say "Time out!" }

DESCRIPTION

When writing programs mixing event programming with OOP, it is very common to employ callbacks that just call some method on some object. I.e.:

$w = AE::io($fh, 0, sub { $obj->data_available_for_reading });

Unfortunately, this style can result in the creation of cyclic data structures that never get freed.

For instance consider the following code:

$obj->{rw} = AE::io($fh, 0, sub { $obj->data_available_for_reading });

The callback is a closure that internally, keeps a reference to $obj. Then a reference to the callback is stored in the watcher object which is itself stored in $obj and so, the cycle is complete.

Method::WeakCallback solves that problem generating callbacks that use a weak reference for the object. Its usage is very simple:

$obj->{rw} = AE::io($fh, 0,
                  weak_method_callback($obj, 'data_available_for_reading'));

If the callback is called after $obj is destroyed it will just do nothing.

Extra arguments to be passed to the method can also be given. I.e.

weak_method_callback($obj, $method, @extra);

# equivalent to:
#   sub { $obj->$method(@extra, @_) };

The module also provides the subroutine weak_method_callback_cached which stores inside an internal cache the generated callbacks greatly improving performance when the same callback (same object, same method) is generated over and over.

Note that weak_method_callback_cached does not accept extra arguments.

EXPORT

None by default.

The subroutines weak_method_callback and weak_method_callback_cached can be imported from this module.

SEE ALSO

curry, AnyEvent.

AUTHOR

Salvador Fandiño, <sfandino@yahoo.com>

COPYRIGHT AND LICENSE

Copyright (C) 2013 by Qindel Formación y Servicios S.L.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.14.2 or, at your option, any later version of Perl 5 you may have available.