feat: add ability to cancel in-flight HTTP requests and manage client lifecycle

This commit is contained in:
sasanktumpati
2024-12-07 13:06:15 +05:30
parent 596cf05576
commit 036bac311c
7 changed files with 169 additions and 92 deletions

View File

@ -0,0 +1,33 @@
import 'package:http/http.dart' as http;
class HttpClientManager {
static final HttpClientManager _instance = HttpClientManager._internal();
final Map<String, http.Client> _clients = {};
factory HttpClientManager() {
return _instance;
}
HttpClientManager._internal();
http.Client createClient(String requestId) {
final client = http.Client();
_clients[requestId] = client;
return client;
}
void cancelRequest(String requestId) {
if (_clients.containsKey(requestId)) {
_clients[requestId]?.close();
_clients.remove(requestId);
}
}
void closeClient(String requestId) {
cancelRequest(requestId);
}
bool hasActiveClient(String requestId) {
return _clients.containsKey(requestId);
}
}

View File

@ -6,14 +6,22 @@ import 'package:seed/seed.dart';
import '../consts.dart';
import '../models/models.dart';
import '../utils/utils.dart';
import 'client_manager.dart';
typedef HttpResponse = http.Response;
Future<(HttpResponse?, Duration?, String?)> request(
HttpRequestModel requestModel, {
String defaultUriScheme = kDefaultUriScheme,
http.Client? client,
String? requestId,
}) async {
final clientManager = HttpClientManager();
http.Client? client;
if (requestId != null) {
client = clientManager.createClient(requestId);
}
(Uri?, String?) uriRec = getValidRequestUri(
requestModel.url,
requestModel.enabledParams,
@ -110,6 +118,9 @@ Future<(HttpResponse?, Duration?, String?)> request(
if (shouldCloseClient) {
client?.close();
}
if (requestId != null) {
clientManager.closeClient(requestId);
}
}
} else {
return (null, null, uriRec.$2);

View File

@ -1 +1,2 @@
export 'http_service.dart';
export 'client_manager.dart';