Capacitor HTTP Plugin and AbortController: Current Cancellation Support?
0 reputation · 09 Sept 2024, 13:23 UTC
0 reputation · 09 Sept 2024, 13:23 UTC
When building mobile or web applications with Capacitor, developers often rely on the HTTP plugin for network requests. A common requirement is to cancel or timeout a request gracefully, especially for large payloads or slow connections. The plugin provides a timeout option that rejects the promise after a specified duration, but the underlying network request continues to run in the background. Additionally, the plugin does not honour an AbortSignal passed via AbortController, and there is no distinct error type for timeouts.
These behaviors create uncertainty about how to efficiently manage resources and provide consistent error handling across platforms. There is no documented plan or open issue tracking the addition of a native cancellation API, leaving developers unsure whether future releases will address this gap.
timeout option or replace it?34775 reputation · 10 Sept 2024, 01:21 UTC
timeout. A native abort implementation would probably use AbortController internally, making timeout a convenience wrapper rather than a replacement.timeout and, on web, wrap the call with your own AbortController to abort the fetch. On iOS/Android, accept that the request may complete in the background; ignore the response after the promise rejects.timeout option rejects the returned promise after the specified milliseconds, but the native HTTP stack (NSURLSession on iOS, OkHttp on Android, fetch on web) continues the request.AbortSignal via the signal option is ignored; the plugin does not wire the signal to the native layer.Adding true cancellation requires platform-specific work: NSURLSessionTask.cancel() on iOS, Call.cancel() on OkHttp, and AbortController on web. The plugin's current architecture treats the native request as fire-and-forget once dispatched, so a cancellation API would need a new code path and likely a minor version bump.
// Web-only true abort
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), 5000);
try {
const res = await Http.get({ url, signal: controller.signal });
} finally {
clearTimeout(id);
}
On native, the same pattern compiles but the signal is ignored; the request continues. Measure with a proxy (Charles, Proxyman) or Android Studio Profiler to confirm background traffic.
Which platforms are you targeting (iOS, Android, web, or all)? The workaround differs: web can achieve true abort today; native cannot without a plugin fork or a community plugin like @capacitor-community/http that may already implement cancellation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.