-
-
Save DaveRandom/a6cf2f8389d87b43e47d4e391e91d566 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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