Skip to content

Commit 2c57d60

Browse files
committed
refactor(ads): improve inline ad caching and resource management
- Add `removeAd` method to temporarily remove ads from cache without disposal - Update `setAd` to use AdService for disposing old ads' resources - Refactor `clearCache` to directly dispose ads instead of using `removeAndDisposeAd` - Update method comments for clarity and accuracy
1 parent 7684dcd commit 2c57d60

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

lib/ads/inline_ad_cache_service.dart

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ class InlineAdCacheService {
7272
/// If [ad] is `null`, it effectively removes the entry for [id].
7373
void setAd(String id, InlineAd? ad) {
7474
if (_cache.containsKey(id) && _cache[id] != null) {
75-
// If an old ad exists for this ID, dispose of its resources.
75+
// If an old ad exists for this ID, dispose of its resources via AdService.
7676
_logger.info(
7777
'Disposing old inline ad for ID "$id" before caching new one.',
7878
);
@@ -88,6 +88,19 @@ class InlineAdCacheService {
8888
}
8989
}
9090

91+
/// Removes an [InlineAd] from the cache without disposing its resources.
92+
///
93+
/// This method should be used when an ad is temporarily removed from the UI
94+
/// (e.g., scrolled off-screen) but its resources might still be needed later.
95+
void removeAd(String id) {
96+
if (_cache.containsKey(id)) {
97+
_cache.remove(id);
98+
_logger.info('Removed inline ad with ID "$id" from cache (no disposal).');
99+
} else {
100+
_logger.info('Inline ad with ID "$id" not found in cache for removal.');
101+
}
102+
}
103+
91104
/// Removes an [InlineAd] from the cache and disposes its resources.
92105
///
93106
/// This method should be used when an ad is permanently removed from the UI
@@ -96,7 +109,7 @@ class InlineAdCacheService {
96109
final ad = _cache[id];
97110
if (ad != null) {
98111
_logger.info('Removing and disposing inline ad with ID "$id".');
99-
_adService.disposeAd(ad);
112+
_adService.disposeAd(ad); // Delegate disposal to AdService
100113
_cache.remove(id);
101114
} else {
102115
_logger.info('Inline ad with ID "$id" not found in cache for disposal.');
@@ -112,9 +125,8 @@ class InlineAdCacheService {
112125
_logger.info(
113126
'Clearing all cached inline ads and disposing their resources.',
114127
);
115-
for (final id in _cache.keys.toList()) {
116-
// Use the new removeAndDisposeAd method for consistent disposal.
117-
removeAndDisposeAd(id);
128+
for (final ad in _cache.values.whereType<InlineAd>()) {
129+
_adService.disposeAd(ad); // Delegate disposal to AdService
118130
}
119131
_cache.clear(); // Ensure cache is empty after disposal attempts.
120132
_logger.info('All cached inline ads cleared.');

0 commit comments

Comments
 (0)