Guest User

Untitled

a guest
Jul 22nd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. package Mojolicious::Plugin::Coro;
  2. use Mojo::Base 'Mojolicious::Plugin';
  3. use Coro;
  4. use Mojo::IOLoop;
  5.  
  6. # Wrap application in coroutine and reschedule main coroutine in event loop
  7. sub register {
  8. my ($self, $app) = @_;
  9.  
  10. my $subscribers = $app->plugins->subscribers('around_dispatch');
  11. unshift @$subscribers, sub {
  12. my $next = shift;
  13. async { $next->() };
  14. };
  15. $app->plugins->unsubscribe('around_dispatch');
  16. $app->hook(around_dispatch => $_) for @$subscribers;
  17.  
  18. Mojo::IOLoop->recurring(0 => sub {cede});
  19. }
  20.  
  21. # Magical class for calling a method non-blocking without a callback and
  22. # rescheduling the current coroutine until it is done
  23. package with::coro;
  24. use Coro;
  25.  
  26. sub AUTOLOAD {
  27. my ($method) = our $AUTOLOAD =~ /^with::coro::(.+)$/;
  28. my ($done, $err, @args);
  29. shift->$method(@_ => sub { $done++; shift; $err = shift; @args = @_ });
  30. cede until $done;
  31. die $err if $err;
  32. return wantarray ? @args : $args[0];
  33. }
  34.  
  35. 1;
Add Comment
Please, Sign In to add comment