Keeping Route Logic Alive

37 views
Skip to first unread message

john

unread,
May 24, 2016, 7:51:42 AM5/24/16
to mojol...@googlegroups.com
Hello,

In my test application (https://github.com/john-/mojo_inotifier) I am
able to have a websocket client receive notifications when a file is
added to a directory.

In order to get this to work I had to define my callback (n the route)
with "our":

our $cb = $watcher->watch(
sub {
my $payload = shift;
$payload->{url} = $c->app->defaults->{audio_url};
$c = $c->send( { json => encode_json($payload) } );
}
);


If I define it with "my" then scope rules cause the variable (and
therefore callback) to be lost.

What confuses me is that I was previously using Mojo::Pg::PubSub and
this works:

my $cb = $c->pubsub->listen(msg => sub {
my ($pubsub, $payload) = @_;
my $msg = decode_json($payload);
$c = $c->send( { json => $msg } );
app->log->debug("item to let client know about (pubsub): $msg->{type}");
});

Why does "my" work in this case but not in the other? It is not clear
to me in reviewing Pg::PubSub code that there is anything different that
would explain this.

John

Heiko Jansen

unread,
May 24, 2016, 8:23:47 AM5/24/16
to Mojolicious
Am Dienstag, 24. Mai 2016 13:51:42 UTC+2 schrieb john:
What confuses me is that I was previously using Mojo::Pg::PubSub and
this works:

I think it works like this:
https://metacpan.org/source/SRI/Mojo-Pg-2.27/lib/Mojo/Pg/PubSub.pm#L14 keeps a reference to the callback inside the Mojo::Pg::PubSub object. And the Mojo::Pg::PubSub object is referenced from Mojolicious. So the reference counter of the callback does not reach 0.
In your Inotifier code nothing outside wsinit() retains a reference to the callback once wsinit() is left (the Inotifier::Model::FileWatch theoretically might, but that object also gets destroyed when leaving wsinit()).

John

unread,
May 24, 2016, 8:29:27 AM5/24/16
to mojol...@googlegroups.com


On May 24, 2016 7:23 AM, "Heiko Jansen" <heiko.j...@gmail.com> wrote:

>
> I think it works like this:
> https://metacpan.org/source/SRI/Mojo-Pg-2.27/lib/Mojo/Pg/PubSub.pm#L14 keeps a reference to the callback inside the Mojo::Pg::PubSub object. And the Mojo::Pg::PubSub object is referenced from Mojolicious. So the reference counter of the callback does not reach 0.
> In your Inotifier code nothing outside wsinit() retains a reference to the callback once wsinit() is left (the Inotifier::Model::FileWatch theoretically might, but that object also gets destroyed when leaving wsinit()).
>

That would explain it.  I may look at a similar approach for my code.

Thanks,

John

Reply all
Reply to author
Forward
0 new messages