Leave a rating/review
In this challenge, you’ll finish the debugging toolbar by connecting the second counter to display on-disk cache hits and making the last toolbar button clear the disk cache.
You should do something similar to what you did in ImageLoader for the in-memory counter.
-
In
ImageDatabase, add anAsyncStreamfor the counter. 2. Set up the stream insetUp(), manually complete it in adeinitand increment the counter when you have an actual disk cache hit. 3. Update the toolbar view to iterate over the stream. 4. Make the last toolbar button clear the disk cache.
Welcome back! Hopefully you had success with this task. Here’s how I did it. It’s similar to what you did in ImageLoader:
In ImageDatabase, I added an AsyncStream for the counter.
@MainActor private(set) var onDiskAccess: AsyncStream<Int>?
private var onDiskAccessCounter = 0 {
didSet { onDiskAcccessContinuation?.yield(onDiskAccessCounter) }
}
private var onDiskAcccessContinuation: AsyncStream<Int>.Continuation?
I set up the stream in the actor’s setUp().
func setUp() async throws {
storage = await DiskStorage()
for fileURL in try await storage.persistedFiles() {
storedImagesIndex.insert(fileURL.lastPathComponent)
}
await imageLoader.setUp()
🟩
let accessStream = AsyncStream<Int> { continuation in
onDiskAcccessContinuation = continuation
}
await MainActor.run { onDiskAccess = accessStream }
🟥
}
And manually completed the stream in a deinitializer
deinit {
onDiskAcccessContinuation?.finish()
}
I incremented the counter in image(_ key:), below the print("In disk cache.") statement:
onDiskAccessCounter += 1
At the end of clear(), I reset the counter to 0 and printed a message:
onDiskAccessCounter = 0
print("Cleared disk cache.")
Then, in BottomToolbar, below the other task, I added a task to iterate over the stream:
.task {
guard let diskAccessSequence = ImageDatabase.shared.onDiskAccess else {
return
}
for await count in diskAccessSequence {
onDiskAccessCount = count
}
}
Finally, I made the first toolbar button clear the disk cache.
Button(action: {
// Clear on-disk cache
🟩
Task {
await ImageDatabase.shared.clear()
}
🟥
}, label: {
Image(systemName: "folder.badge.minus")
})
Now the disk counter works. When I clear both the disk and memory caches, the app fetches the images from the server.
Congratulate yourself on a super useful debugging tool!