From 37de4960afb2402432ee7691835718d696c6f5be Mon Sep 17 00:00:00 2001 From: Dan Field Date: Fri, 8 Jul 2022 00:52:05 -0700 Subject: [PATCH] Remove listeners from pending images when clearing cache (#107276) --- .../flutter/lib/src/painting/image_cache.dart | 3 ++ .../test/painting/image_cache_test.dart | 31 +++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/flutter/lib/src/painting/image_cache.dart b/packages/flutter/lib/src/painting/image_cache.dart index 5e6101cb26..37b3bc6601 100644 --- a/packages/flutter/lib/src/painting/image_cache.dart +++ b/packages/flutter/lib/src/painting/image_cache.dart @@ -195,6 +195,9 @@ class ImageCache { image.dispose(); } _cache.clear(); + for (final _PendingImage pendingImage in _pendingImages.values) { + pendingImage.removeListener(); + } _pendingImages.clear(); _currentSizeBytes = 0; } diff --git a/packages/flutter/test/painting/image_cache_test.dart b/packages/flutter/test/painting/image_cache_test.dart index 483049807f..b8a951de26 100644 --- a/packages/flutter/test/painting/image_cache_test.dart +++ b/packages/flutter/test/painting/image_cache_test.dart @@ -179,6 +179,10 @@ void main() { return completer1; })! as TestImageStreamCompleter; + // Make the image seem live. + final ImageStreamListener listener = ImageStreamListener((_, __) {}); + completer1.addListener(listener); + expect(imageCache.statusForKey(testImage).pending, true); expect(imageCache.statusForKey(testImage).live, true); imageCache.clear(); @@ -346,10 +350,10 @@ void main() { imageCache.clear(); expect(imageCache.statusForKey(testImage1).pending, false); - expect(imageCache.statusForKey(testImage1).live, true); + expect(imageCache.statusForKey(testImage1).live, false); completer1.testSetImage(testImage1); - expect(imageCache.statusForKey(testImage1).keepAlive, true); + expect(imageCache.statusForKey(testImage1).keepAlive, false); expect(imageCache.statusForKey(testImage1).live, false); imageCache.putIfAbsent(testImage2, () => completer2); @@ -602,4 +606,27 @@ void main() { imageInfo.dispose(); expect(testImage.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 + + test('clear does not leave pending images stuck', () async { + final ui.Image testImage = await createTestImage(width: 8, height: 8); + + final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); + + imageCache.putIfAbsent(testImage, () { + return completer1; + }); + + expect(imageCache.statusForKey(testImage).pending, true); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, false); + + imageCache.clear(); + + // No one else is listening to the completer. It should not be considered + // live anymore. + + expect(imageCache.statusForKey(testImage).pending, false); + expect(imageCache.statusForKey(testImage).live, false); + expect(imageCache.statusForKey(testImage).keepAlive, false); + }); }