Created
August 31, 2016 12:49
-
-
Save earltedly/693664142b368d5ace881e591516cd2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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