Skip to content

Instantly share code, notes, and snippets.

@earltedly
Created August 31, 2016 12:49
Show Gist options
  • Save earltedly/693664142b368d5ace881e591516cd2e to your computer and use it in GitHub Desktop.
Save earltedly/693664142b368d5ace881e591516cd2e to your computer and use it in GitHub Desktop.
import Foundation
import RxSwift
import RxCocoa
class ImageCache {
static let sharedInstance = ImageCache()
private let observableCache = NSCache()
private let imageCache = NSCache()
func loadImage(url: NSURL) -> Observable<UIImage?> {
return Observable.deferred {
if let image = self.imageCache[url] as? UIImage {
return Observable.just(image).observeOn(MainScheduler.instance).debug("Just")
}
if url.absoluteString == "" {
return Observable.just(nil)
}
if let observable = self.observableCache[url] as? Observable<UIImage?> {
return observable
}
let observable: Observable<UIImage?> = NSURLSession.sharedSession()
.rx_data(NSURLRequest(URL: url))
.map { data in
return UIImage(data: data)
}
.debug("NSURLRequest")
.shareReplay(1)
.observeOn(MainScheduler.instance)
.doOnNext { (image) in
guard let image = image else { return }
self.imageCache[url] = image
}
self.observableCache[url] = observable
return observable
}
}
}
private extension NSCache {
subscript(key: AnyObject) -> AnyObject? {
get {
return objectForKey(key)
}
set {
if let value: AnyObject = newValue {
setObject(value, forKey: key)
} else {
removeObjectForKey(key)
}
}
}
}
2016-08-31 13:45:12.437: NSURLRequest -> subscribed
2016-08-31 13:45:13.259: NSURLRequest -> Event Next(Optional(<UIIma...2791bb0>, {80, 80}))
2016-08-31 13:45:13.259: NSURLRequest -> Event Completed
2016-08-31 13:45:13.259: NSURLRequest -> disposed
2016-08-31 13:45:14.663: Just -> subscribed
2016-08-31 13:45:14.664: Just -> Event Next(Optional(<UIIma...2791bb0>, {80, 80}))
2016-08-31 13:45:14.664: Just -> Event Completed
2016-08-31 13:45:14.664: Just -> disposed
2016-08-31 13:45:14.722: Just -> subscribed
2016-08-31 13:45:14.722: Just -> Event Next(Optional(<UIIma...2791bb0>, {80, 80}))
2016-08-31 13:45:14.722: Just -> Event Completed
2016-08-31 13:45:14.722: Just -> disposed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment