1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 21:31:18 +01:00
amp/lib/CancellationTokenSource.php

62 lines
1.8 KiB
PHP
Raw Normal View History

<?php
namespace Amp;
/**
* A cancellation token source provides a mechanism to cancel operations.
*
* Cancellation of operation works by creating a cancellation token source and passing the corresponding token when
* starting the operation. To cancel the operation, invoke `CancellationTokenSource::cancel()`.
*
* Any operation can decide what to do on a cancellation request, it has "don't care" semantics. An operation SHOULD be
* aborted, but MAY continue. Example: A DNS client might continue to receive and cache the response, as the query has
* been sent anyway. An HTTP client would usually close a connection, but might not do so in case a response is close to
* be fully received to reuse the connection.
*
* **Example**
*
* ```php
2017-05-16 21:46:52 +02:00
* $tokenSource = new CancellationTokenSource;
* $token = $tokenSource->getToken();
*
2020-08-23 09:18:28 -05:00
* $response = yield $httpClient->request("https://example.com/pipeline", $token);
* $responseBody = $response->getBody();
*
* while (($chunk = yield $response->read()) !== null) {
* // consume $chunk
*
* if ($noLongerInterested) {
* $cancellationTokenSource->cancel();
* break;
* }
* }
* ```
*
* @see CancellationToken
* @see CancelledException
*/
2018-06-18 20:00:01 +02:00
final class CancellationTokenSource
{
private Internal\CancellableToken $source;
private CancellationToken $token;
2018-06-18 20:00:01 +02:00
public function __construct()
{
$this->source = new Internal\CancellableToken;
$this->token = new Internal\WrappedCancellationToken($this->source);
}
2018-06-18 20:00:01 +02:00
public function getToken(): CancellationToken
{
return $this->token;
}
2017-06-13 12:41:47 -05:00
/**
* @param \Throwable|null $previous Exception to be used as the previous exception to CancelledException.
*/
public function cancel(?\Throwable $previous = null): void
2018-06-18 20:00:01 +02:00
{
$this->source->cancel($previous);
}
}