Skip to content

Commit 82f10f9

Browse files
committed
Refactor for await in web runtime to streamcontroller
Signed-off-by: Justus Fluegel <[email protected]>
1 parent 1df55ab commit 82f10f9

File tree

1 file changed

+34
-27
lines changed

1 file changed

+34
-27
lines changed

cached_network_image_web/lib/cached_network_image_web.dart

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -115,39 +115,46 @@ class ImageLoader implements platform.ImageLoader {
115115
int? maxWidth,
116116
Map<String, String>? headers,
117117
VoidCallback evictImage,
118-
) async* {
119-
try {
120-
await for (final result in cacheManager.getFileStream(
121-
url,
122-
key: cacheKey,
123-
withProgress: true,
124-
headers: headers,
125-
)) {
126-
if (result is DownloadProgress) {
118+
) {
119+
var streamController = StreamController<ui.Codec>();
120+
121+
final stream = cacheManager.getFileStream(
122+
url,
123+
withProgress: true,
124+
headers: headers,
125+
key: cacheKey,
126+
);
127+
128+
stream.listen(
129+
(event) {
130+
if (event is DownloadProgress) {
127131
chunkEvents.add(
128132
ImageChunkEvent(
129-
cumulativeBytesLoaded: result.downloaded,
130-
expectedTotalBytes: result.totalSize,
133+
cumulativeBytesLoaded: event.downloaded,
134+
expectedTotalBytes: event.totalSize,
131135
),
132136
);
133137
}
134-
if (result is FileInfo) {
135-
final file = result.file;
136-
final bytes = await file.readAsBytes();
137-
final decoded = await decode(bytes);
138-
yield decoded;
138+
if (event is FileInfo) {
139+
event.file
140+
.readAsBytes()
141+
.then((value) => decode(value).then(streamController.add));
139142
}
140-
}
141-
} on Object {
142-
// Depending on where the exception was thrown, the image cache may not
143-
// have had a chance to track the key in the cache at all.
144-
// Schedule a microtask to give the cache a chance to add the key.
145-
scheduleMicrotask(() {
146-
evictImage();
147-
});
148-
rethrow;
149-
}
150-
await chunkEvents.close();
143+
},
144+
onError: (e, st) {
145+
scheduleMicrotask(() {
146+
evictImage();
147+
});
148+
streamController.addError(e, st);
149+
},
150+
onDone: () async {
151+
streamController.close();
152+
chunkEvents.close();
153+
},
154+
cancelOnError: true,
155+
);
156+
157+
return streamController.stream;
151158
}
152159

153160
Future<ui.Codec> _loadAsyncHtmlImage(

0 commit comments

Comments
 (0)