From 5c89102716d082316f936ca9133f1953eae29bea Mon Sep 17 00:00:00 2001 From: VIVEK <133876017+nope3472@users.noreply.github.com> Date: Sun, 16 Feb 2025 17:41:34 +0530 Subject: [PATCH] fix: Update history_utils.dart --- lib/utils/history_utils.dart | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/utils/history_utils.dart b/lib/utils/history_utils.dart index d1c3dbbc..c4658519 100644 --- a/lib/utils/history_utils.dart +++ b/lib/utils/history_utils.dart @@ -1,3 +1,5 @@ + +import 'package:flutter/foundation.dart'; import 'package:apidash/models/models.dart'; import 'package:apidash/consts.dart'; import 'convert_utils.dart'; @@ -130,3 +132,47 @@ DateTime? getRetentionDate(HistoryRetentionPeriod? retentionPeriod) { return null; } } + +// ---------------------------------------------------------------------- +// New code: Offload expired history cleanup to a background isolate using compute. +// ---------------------------------------------------------------------- + +// Top-level function to run in the background isolate. +// This function expects a serialized Map where keys are DateTime +// represented as epoch milliseconds strings and values are lists of HistoryMetaModel JSON. +Map _filterExpiredHistory(Map params) { + final String retentionDateStr = params['retentionDate']; + final DateTime retentionDate = DateTime.parse(retentionDateStr); + final Map serializedHistory = + Map.from(params['history']); + + // Remove expired history entries. + serializedHistory.removeWhere((key, value) { + final DateTime date = + DateTime.fromMillisecondsSinceEpoch(int.parse(key)); + return date.isBefore(retentionDate); + }); + return serializedHistory; +} + +// Asynchronous helper that offloads filtering to a background isolate. +Future>> clearExpiredHistoryAsync( + Map> historySequence, + DateTime retentionDate) async { + // Serialize: convert DateTime keys to strings and each HistoryMetaModel to JSON. + final Map serialized = historySequence.map((key, value) => + MapEntry(key.millisecondsSinceEpoch.toString(), + value.map((item) => item.toJson()).toList())); + + // Offload the filtering using compute. + final result = await compute(_filterExpiredHistory, { + 'history': serialized, + 'retentionDate': retentionDate.toIso8601String(), + }); + + // Deserialize: convert keys back to DateTime and JSON back to HistoryMetaModel. + return result.map((key, value) => MapEntry( + DateTime.fromMillisecondsSinceEpoch(int.parse(key)), + List.from( + (value as List).map((item) => HistoryMetaModel.fromJson(item))))); +}