ArnaudPiroelle
10/6/2016 - 7:09 PM

Examples.swift


let thumbnail: UIImageView = ...
thumbnail.rx_setImage(url: URL(string:  currentVideo.thumbnail)!, placeholderImage: UIImage(named: "Placeholder Video"))

RxNetwork.withData<Model>(URLRequest(url: url!))
         .subscribe(onNext: { data in
                // Use data as Data
            })

let videoObservable : Observable<Video> = RxNetwork.withJSON(URLRequest(url: url!))
videoObservable.subscribe(onNext: { data in
                // Use data as Video
            })
import Foundation
import RxSwift
import Unbox

class RxNetwork {
    
    static func withData(_ request: URLRequest?) -> Observable<Data> {
        guard let valideRequest = request else { return Observable.empty() }
        
        return URLSession.shared.rx.data(valideRequest)
    }
    
    static func withJSON<T : Unboxable>(_ request: URLRequest) -> Observable<T> {
        return withData(request)
            .map { (data: Data) -> T in try Unbox(data: data) }
        
    }
}
import Foundation
import RxSwift
import Unbox

extension UIImageView {
    
    struct LoaderWrapper {
        static var SetImageFetcherKey = 0
        
        let networkObservable: Disposable
    }
    
    private var rx_wrapper : LoaderWrapper? {
        get {
            return objc_getAssociatedObject(self, &LoaderWrapper.SetImageFetcherKey) as? LoaderWrapper
        }
        
        set(wrapper) {
            objc_setAssociatedObject(self, &LoaderWrapper.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func rx_setImage(url: URL?, placeholderImage: UIImage?) {
        
        rx_cancelSetImage()
        
        if let placeholder = placeholderImage {
            self.image = placeholder
        }
        
        let imageObservable = RxNetwork.withData(URLRequest(url: url!))
            .observeOn(MainScheduler.instance)
            .subscribeOn(ConcurrentMainScheduler.instance)
            .subscribe(onNext: {
                data in
                
                self.image = UIImage(data: data)
            })

        
        rx_wrapper = LoaderWrapper(networkObservable: imageObservable)
        
    }
    
    func rx_cancelSetImage() {
        if let networkObservable = rx_wrapper?.networkObservable {
            networkObservable.dispose()
        }
    }
}