Handling image caching in Combine with Swift involves using URLSession alongside Combine’s publisher and subscriber model. Here’s a basic example of how you can implement image caching to optimize your image loading performance in a Swift application. This method ensures that images are fetched from the cache when available, reducing network calls and improving user experience.
import Combine
import UIKit
class ImageLoader {
private var cancellables = Set()
private var imageCache = NSCache()
func loadImage(from url: URL) -> AnyPublisher {
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
return Just(cachedImage).eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.map(UIImage.init)
.handleEvents(receiveOutput: { [weak self] image in
if let image = image {
self?.imageCache.setObject(image, forKey: url.absoluteString as NSString)
}
})
.replaceError(with: nil)
.eraseToAnyPublisher()
}
}
// Usage example
let imageLoader = ImageLoader()
let imageURL = URL(string: "https://example.com/image.png")!
imageLoader.loadImage(from: imageURL)
.sink(receiveValue: { image in
// Update UI with the loaded image
print(image)
})
.store(in: &imageLoader.cancellables)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?