Description
In 2020, an abort
method was added to the HttpClientRequest
object in the dart:io
library, allowing us to abort ongoing HTTP requests (see #22265, which is now closed). However, as per a comment by @sgjesse on that issue:
The call to getUrl completes when the connection has been established. This can take time, so it should be possible to cancel that part. Currently there is no object to hook up any abort call to. A Future is returned, but futures cannot be canceled/aborted.
This is still true. Whilst we can now abort the request once it starts, we can't abort during the initial stage in which a connection is established. In my testing, I frequently encounter a situation where the device has a poor internet connection, and thus gets stuck at this point, with no way for the user to abort it.
I think there should be a better solution for aborting requests which does not only abort one part of the request timeline. A potential solution would be some sort of cancellation token which could be passed into the initial openUrl
(or getUrl
, postUrl
, etc.) call, something also suggested by @sgjesse in that same comment:
One option could be to add an additional argument to getUrl (and friends) where the called can pass an object where getUrl can place a callback for aborting the HTTP transaction, e.g.:
var c = new HttpClientConnectionController();
new Timer(new Duration(seconds: 2), () {
c.cancel();
});
client.getUrl(Uri.parse("http://www.example.com/"), controller: c)
.then((HttpClientRequest request) {
...
.catchError((e) => ..., test: (e) => e is CancledException);