Slide 1

Slide 1 text

Taming Delegates in RxSwift Created by Faiz Mokhtar

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

We can make use of DelegateProxy and DelegateProxyType! Created by Faiz Mokhtar

Slide 4

Slide 4 text

How to implement Created by Faiz Mokhtar

Slide 5

Slide 5 text

1. Register and create proxy class extension CLLocationManager: HasDelegate {} class RxCLLocationManagerDelegateProxy: DelegateProxy, DelegateProxyType, CLLocationManagerDelegate { } Created by Faiz Mokhtar

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

and register known implementation static func registerKnownImplementations() { register { RxCLLocationManagerDelegateProxy(locationManager: $0) } } Created by Faiz Mokhtar

Slide 8

Slide 8 text

3. Implement the proxy and expose it to rx namespace extension Reactive where Base: CLLocationManager { var delegate: DelegateProxy { RxCLLocationManagerDelegateProxy.proxy(for: base) } } Created by Faiz Mokhtar

Slide 9

Slide 9 text

4. Implement the observables for the delegate methods var authorizationStatus: Observable { delegate.methodInvoked(#selector(CLLocationManagerDelegate .locationManager(_:didChangeAuthorization:))) .map { parameters in CLAuthorizationStatus(rawValue: parameters[1] as! Int32)! } .startWith(CLLocationManager.authorizationStatus()) } Created by Faiz Mokhtar

Slide 10

Slide 10 text

That's it! Now, the observables you've define should be available in rx namespace Created by Faiz Mokhtar

Slide 11

Slide 11 text

When to use it? Created by Faiz Mokhtar

Slide 12

Slide 12 text

Demo Created by Faiz Mokhtar

Slide 13

Slide 13 text

Further references → RxCocoa/DelegateProxy → RxCocoa/RxSearchBarDelegateProxy → RxCCocoa/RxScrollViewDelegateProxy → How Delegate Proxy works in RxSwift Created by Faiz Mokhtar

Slide 14

Slide 14 text

Thanks! Created by Faiz Mokhtar