Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Mojolicious::Plugin::Coro;
- use Mojo::Base 'Mojolicious::Plugin';
- use Coro;
- use Mojo::IOLoop;
- # Wrap application in coroutine and reschedule main coroutine in event loop
- sub register {
- my ($self, $app) = @_;
- my $subscribers = $app->plugins->subscribers('around_dispatch');
- unshift @$subscribers, sub {
- my $next = shift;
- async { $next->() };
- };
- $app->plugins->unsubscribe('around_dispatch');
- $app->hook(around_dispatch => $_) for @$subscribers;
- Mojo::IOLoop->recurring(0 => sub {cede});
- }
- # Magical class for calling a method non-blocking without a callback and
- # rescheduling the current coroutine until it is done
- package with::coro;
- use Coro;
- sub AUTOLOAD {
- my ($method) = our $AUTOLOAD =~ /^with::coro::(.+)$/;
- my ($done, $err, @args);
- shift->$method(@_ => sub { $done++; shift; $err = shift; @args = @_ });
- cede until $done;
- die $err if $err;
- return wantarray ? @args : $args[0];
- }
- 1;
Add Comment
Please, Sign In to add comment