Subject: | Support for ->retain |
Instead of having to use tools such as ->adopt_future and Variable::Disposition::retain_future, might as well have a simple method or two on Future.pm itself?
(this has been suggested a few times before but I didn't see an existing method or patch, so I figured it was worth raising an RT)
Subject: | 2017-11-23-future-retain.diff |
commit 4e214aeb5ac223fc11461c6611560da4f69e9ac1
Author: Tom Molesworth <TEAM@cpan.org>
Date: Thu Nov 23 01:33:51 2017 +0800
Support for ->retain method
diff --git a/lib/Future.pm b/lib/Future.pm
index 4d5a01a..ef2848d 100644
--- a/lib/Future.pm
+++ b/lib/Future.pm
@@ -1490,6 +1490,20 @@ sub without_cancel
return $new;
}
+=head2 retain
+
+ Future->needs_all($f1, $f2)->retain;
+
+Creates a cycle that causes this C<Future> to stay alive until it resolves.
+
+=cut
+
+sub retain
+{
+ my $self = shift;
+ return $self->on_ready(sub { undef $self });
+}
+
=head1 CONVERGENT FUTURES
The following constructors all take a list of component futures, and return a
diff --git a/t/01future.t b/t/01future.t
index c638627..64dd360 100644
--- a/t/01future.t
+++ b/t/01future.t
@@ -259,4 +259,18 @@ use Future;
$f->cancel;
}
+# retain
+{
+ my @args;
+ for my $method (qw(cancel done fail)) {
+ my $f = Future->new;
+ is_oneref($f, 'start with refcount 1');
+ is($f->retain, $f, '->retain returns original Future');
+ is_refcount($f, 2, 'refcount is now increased');
+ ok($f->$method(@args), 'can call ->' . $method);
+ is_oneref($f, 'refcount drops when resolved');
+ push @args, 'x';
+ }
+}
+
done_testing;