Skip to content

Instantly share code, notes, and snippets.

@DaveRandom
Created April 27, 2017 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaveRandom/a6cf2f8389d87b43e47d4e391e91d566 to your computer and use it in GitHub Desktop.
Save DaveRandom/a6cf2f8389d87b43e47d4e391e91d566 to your computer and use it in GitHub Desktop.
<?php
final class CancellationTokenSource
{
private $deferred;
public $token;
public function cancel()
{
$this->deferred->fail(new TaskCancelledException);
}
public function __construct()
{
$this->deferred = new Deferred;
$this->token = new CancellationToken($this->deferred->promise);
}
}
final class CancellationToken
{
private $callbacks = [];
public function __construct(Promise $promise)
{
$callbacks = &$this->callbacks;
$promise->onResolve(static function () use($callbacks) {
foreach ($callbacks as $callback) {
$callback();
}
});
}
public function onCancel(callable $callback)
{
$this->callbacks[] = $callback;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment