Last active
April 15, 2016 08:48
-
-
Save ChrisLowe-Takor/9e6b7f1d519b62d466f8 to your computer and use it in GitHub Desktop.
RxSwift reactive extension for MGLMapViewDelegate methods
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 Mapbox | |
import RxCocoa | |
import RxSwift | |
import UIKit | |
class RxMGLMapViewDelegateProxy: DelegateProxy, MGLMapViewDelegate, DelegateProxyType { | |
class func currentDelegateFor(object: AnyObject) -> AnyObject? { | |
let mapView: MGLMapView = castOrFatalError(object) | |
return mapView.delegate | |
} | |
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { | |
let mapView: MGLMapView = castOrFatalError(object) | |
mapView.delegate = castOptionalOrFatalError(delegate) | |
} | |
} | |
extension MGLMapView { | |
public var rx_delegate: DelegateProxy { | |
return proxyForObject(self) as RxMGLMapViewDelegateProxy | |
} | |
public var rx_mapViewReigionDidChange: Observable<MGLMapView> { | |
return rx_delegate.observe("mapView:regionDidChangeAnimated:") | |
.map { a in return a[0] as! MGLMapView } | |
} | |
public var rx_mapViewReigionWillChange: Observable<MGLMapView> { | |
return rx_delegate.observe("mapView:regionWillChangeAnimated:") | |
.map { a in return a[0] as! MGLMapView } | |
} | |
public var rx_mapViewReigionIsChanging: Observable<MGLMapView> { | |
return rx_delegate.observe("mapViewRegionIsChanging:") | |
.map { a in return a[0] as! MGLMapView } | |
} | |
} | |
// workaround for Swift compiler bug, cheers compiler team :) | |
func castOptionalOrFatalError<T>(value: AnyObject?) -> T? { | |
if value == nil { | |
return nil | |
} | |
let v: T = castOrFatalError(value) | |
return v | |
} | |
func castOrFatalError<T>(value: AnyObject!, message: String) -> T { | |
let maybeResult: T? = value as? T | |
guard let result = maybeResult else { | |
rxFatalError(message) | |
return maybeResult! | |
} | |
return result | |
} | |
func castOrFatalError<T>(value: AnyObject!) -> T { | |
let maybeResult: T? = value as? T | |
guard let result = maybeResult else { | |
rxFatalError("Failure converting from \(value) to \(T.self)") | |
return maybeResult! | |
} | |
return result | |
} | |
func rxFatalErrorAndDontReturn<T>(lastMessage: String) -> T { | |
rxFatalError(lastMessage) | |
return (nil as T!)! | |
} | |
func rxFatalError(lastMessage: String) { | |
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. | |
fatalError(lastMessage) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment