Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Taming Delegates in RxSwift

Taming Delegates in RxSwift

Presented during Boost iOS knowledge sharing session

Faiz Mokhtar

July 07, 2021
Tweet

More Decks by Faiz Mokhtar

Other Decks in Programming

Transcript

  1. Hypothetical problem We want to chain our observable events but

    we're unable to do so since some of the methods uses delegate pattern. How can we make it more reactive? Created by Faiz Mokhtar
  2. 1. Register and create proxy class extension CLLocationManager: HasDelegate {}

    class RxCLLocationManagerDelegateProxy: DelegateProxy<CLLocationManager, CLLocationManagerDelegate>, DelegateProxyType, CLLocationManagerDelegate { } Created by Faiz Mokhtar
  3. 2. Initialize parent object weak public private(set) var locationManager: CLLocationManager?

    public init(locationManager: ParentObject) { self.locationManager = locationManager super.init(parentObject: locationManager, delegateProxy: RxCLLocationManagerDelegateProxy.self) } Created by Faiz Mokhtar
  4. and register known implementation static func registerKnownImplementations() { register {

    RxCLLocationManagerDelegateProxy(locationManager: $0) } } Created by Faiz Mokhtar
  5. 3. Implement the proxy and expose it to rx namespace

    extension Reactive where Base: CLLocationManager { var delegate: DelegateProxy<CLLocationManager, CLLocationManagerDelegate> { RxCLLocationManagerDelegateProxy.proxy(for: base) } } Created by Faiz Mokhtar
  6. 4. Implement the observables for the delegate methods var authorizationStatus:

    Observable<CLAuthorizationStatus> { delegate.methodInvoked(#selector(CLLocationManagerDelegate .locationManager(_:didChangeAuthorization:))) .map { parameters in CLAuthorizationStatus(rawValue: parameters[1] as! Int32)! } .startWith(CLLocationManager.authorizationStatus()) } Created by Faiz Mokhtar