NAME

Promises::Channel - a coordination channel implemented with Promises

VERSION

version 0.01

SYNOPSIS

  use Promises::Channel qw(channel);

  my $channel = channel
    limit => 4;


  # Use to invert control on an AnyEvent::Handle
  $ae_handle->on_read(sub {
    my $handle = shift;

    $handle->push_read(line => sub {
      my ($handle, $line) = @_;
      $channel->put($line);
    });
  });

  $ae_handle->on_error(sub {
    $channel->shutdown;
  });


  # See notes about recursion in Promises::Cookbook::Recursion
  sub reader {
    my ($channel, $line) = @_;
    do_stuff $line;

    # Queue the next read
    $channel->get->then(\&reader);
  }

  $channel->get->then(\&reader);

DESCRIPTION

A Promises::Channel is a FIFO queue that produces Promises::Promises which resolve to the items added to the queue.

ATTRIBUTES

limit

Sets an upper boundary on the number of items which may be queued at a time. If this limit is reached, the promise returned by the next call to "put" will not be resolved until there has been a corresponding call to "get" (or the channel has been "shutdown".

is_shutdown

Returns true if the channel has been shutdown. The channel will be automatically shutdown and drained when demolished.

METHODS

size

Returns the number of items in the queue. This number is not adjusted to reflect any queued waiters.

is_full

If a "limit" has been set, returns true if the channel is full and cannot immediately accept new items.

is_empty

Returns true if there are no items in the queue and there are no pending deliveries of items from deferred "put"s.

put

Adds one or more items to the channel and returns a Promises::Promise that will resolve to the channel instance after the item has been added (which may be deferred if "limit" has been set).

get

Returns a Promises::Promise which will resolve to the channel and the next item queued in the channel.

  $chan->get->then(sub {
    my ($chan, $item) = @_;
    ...
  });

shutdown

Closes the queue. This does not prevent new items from being added. However, future calls to "get" will be resolved immediately with undef. Any previously deferred calls to get will be immediately resolved until the channel is empty, after which any remaining deferrals will be resolved with undef.

When the channel goes out of scope, it will be shutdown and drained automatically.

EXPORTS

Nothing is exported by default.

chan

channel

Sugar for calling the default constructor. The following lines are equivalent.

  my $ch = chan;
  my $ch = channel;
  my $ch = Promises::Channel->new;

AUTHOR

Jeff Ober <sysread@fastmail.fm>

COPYRIGHT AND LICENSE

This software is copyright (c) 2018 by Jeff Ober.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.