所有文章

RxSwift 探索之旅 · 12

擴充 UIKit:Binder、Reactive Extensions 與 DelegateProxy

拆解 Binder、ControlEvent、ControlProperty,並以 CLLocationManager 為例實作 DelegateProxy。

本篇目錄 · 8 個章節

我們一路上使用各種Rx版的UIKit,其實都是透過Extension,這裡來聊聊,到底要如何自訂Rx Extensions。

Binder

Binder是一種Observer,它有幾個特徵

  1. 不處理.error,只處理.next
  2. 預設在MainScheduler處理

我們以UIControl為例,打開UIControl+Rx.swift,第一段就是對isEnable做封裝

public var isEnabled: Binder<Bool> {
return Binder(self.base) { control, value in
control.isEnabled = value
}
}

Binder在初始化時會需要給定一個closure,參數包含兩個,第一個是Target,也就是Base,以上範例就是UIControl,第二參數是Value

既然是Observer,只用起來會像這樣

Observable.of(true).bind(to: button.rx.isEnabled).disposed(by: disposeBag)

ControlEvent

ControlEvent是一種Observable的變化型,它有幾個特徵

  1. 不會產生error
  2. 在MainScheduler運行,同以下意思
Observable
.subscribeOn(MainScheduler.instance)
.observeOn(MainScheduler.instance)

就以UIButton作為例子,打開UIButton+Rx.swift,第一段就是對於.touchUpInside事件的封裝

extension Reactive where Base: UIButton {
/// Reactive wrapper for `TouchUpInside` control event.
public var tap: ControlEvent<Void> {
return controlEvent(.touchUpInside)
}
}

其中Base就是代表我們要擴展的物件

Reactive.swift
public struct Reactive<Base> {
...
}

既然ControlEvent是一種Observable的變化型,使用起來就可以像這樣串

button.rx.tap.bind(to: observer).disposed(by: disposeBag)

ControlProperty

ControlProperty可以是Observable,也可以是Observer,有幾個特徵

  1. 不處理.error
  2. 在MainScheduler運行
  3. 可共享,即是shareRelay(1)

就以UIButton作為例子,打開UISwitch+Rx.swift,第一段就是對isOn的封裝

UISwitch+Rx.swift
public var isOn: ControlProperty<Bool> {
return value
}
public var value: ControlProperty<Bool> {
return base.rx.controlPropertyWithDefaultEvents(
getter: { uiSwitch in
uiSwitch.isOn
}, setter: { uiSwitch, value in
uiSwitch.isOn = value
}
)
}

其中controlPropertyWithDefaultEvents是個重點,它位於『UIControl+Rx.swift』,當.valueChanged時,執行getter或setter

UIControl+Rx.swift
internal func controlPropertyWithDefaultEvents<T>(
editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged],
getter: @escaping (Base) -> T,
setter: @escaping (Base, T) -> Void
) -> ControlProperty<T> {
return controlProperty(
editingEvents: editingEvents,
getter: getter,
setter: setter
)
}

因為被定義為internal,所以要擴充自訂的class時,無法直接參照上面程式碼,可以改成下面這樣

extension Reactive where Base: RadioButton {
var isOn: ControlProperty<Bool> {
return value
}
var value: ControlProperty<Bool> {
return controlProperty(
editingEvents: [.allEditingEvents, .valueChanged],
getter: { radioButton in
radioButton.isOn
},
setter: { radioButton, value in
radioButton.isOn = value
}
)
}
}

封裝Function

這部分就是Observable 的生命週期與建立方式提過的Observable.create去實現,在『URLSession+Rx.swift』中可以看到範例

public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
return Observable.create { observer in
...
let task = self.base.dataTask(with: request) { data, response, error in
...
observer.on(.next((httpResponse, data)))
observer.on(.completed)
}
task.resume()
return Disposables.create(with: task.cancel)
}
}

自訂operator

這部分是從RxSwift: Reactive Programming with Swift書中章節所介紹,我覺得之後可能很有用,於是我將其簡化再簡化做個分享。假如在有一全域變數Cache,我能在任何為Observable<Int>的Observable使用此storeCache操作,將其存到Cache變數中,我可以這樣寫

var Cache: Int = 0
extension ObservableType where Element == Int {
func storeCache() -> Observable<Element> {
return self.do(onNext: {
Cache = $0
})
}
}

用起來就會像這樣

Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
.storeCache()
.subscribe(onNext: { _ in
print("Cache: \(Cache)")
})
.disposed(by: disposeBag)

延續Reactive Extensions,在iOS設計中,delegate pattern很常見,但要套用到functional programming,似乎有點不知道串,所以,我們來看看,大神們是怎麼將CLLocationManager封裝成Rx的樣子,官方程式在RxSwift/RxCLLocationManagerDelegateProxy.swift和CLLocationManager+Rx.swift

DelegateProxy

原本我們做delegate時,只能給一個人,但封裝之後,delegate被佔據,我們還是可以使用setDelegate跟給Rx Observable使用,這是因為有DelegateProxy,顧名思義是代理Delegate。

下方流程圖被記錄在DelegateProxyType.swift當中,UIScrollView的delegate交給proxy,再由proxy去實現delegate內容,所以對外來說,只能接觸到proxy。

DelegateProxyType.swift
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+

RxCLLocationManagerDelegateProxy

第一步,要為CLLocationManager建立DelegateProxy,需要繼承DelegateProxy<CLLocationManager, CLLocationManagerDelegate>,實作DelegateProxyType跟CLLocationManagerDelegate

RxCLLocationManagerDelegateProxy
: DelegateProxy<CLLocationManager, CLLocationManagerDelegate>
, DelegateProxyType
, CLLocationManagerDelegate {

第二步,完成init()部分

public init(locationManager: CLLocationManager) {
super.init(parentObject: locationManager, delegateProxy: RxCLLocationManagerDelegateProxy.self)
}

這部分被定義在DelegateProxy.swift當中

public init<Proxy: DelegateProxyType>(parentObject: ParentObject, delegateProxy: Proxy.Type)
where Proxy: DelegateProxy<ParentObject, Delegate>, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate {
…
}

第三步,CLLocationManager需要實現HasDelegate protocol,並將Delegate型態具體採用為CLLocationManagerDelegate

extension CLLocationManager: HasDelegate {
public typealias Delegate = CLLocationManagerDelegate
}

如此一來DelegateProxyType就可以set, get Delegate

extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate {
public static func currentDelegate(for object: ParentObject) -> Delegate? {
return object.delegate
}
public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) {
object.delegate = delegate
}
}

第四步 呼叫DelegateProxyType中的register<Parent>,將RxCLLocationManagerDelegateProxy的instance儲存到DelegateProxyFactory

public static func registerKnownImplementations() {
self.register { RxCLLocationManagerDelegateProxy(locationManager: $0) }
}

(使用起來很簡單,但看這邊的Source Code是真的看不太懂…)

第四步已經完成DelegateProxy的建立,已經可以進入到下一段,對CLLocationManager進行Rx extension。

CLLocationManager+Rx

第五步 對CLLocationManager進行Rx extension,並透過proxy來取得RxCLLocationManagerDelegateProxy,在文件中明確提醒,絕對不要直接初始化RxCLLocationManagerDelegateProxy,而是要用proxy來取得。

extension Reactive where Base: CLLocationManager {
public var delegate: DelegateProxy<CLLocationManager, CLLocationManagerDelegate> {
RxCLLocationManagerDelegateProxy.proxy(for: base)
}
}

第六步 現在就可以針對每一個delegate方法進行Rx化,將delegate的方法轉換成Observable,實際做法有兩種,第一種是在RxCLLocationManagerDelegateProxy.swift所看到的,實現CLLocationManagerDelegate方法,並以Subject作傳遞

internal lazy var didUpdateLocationsSubject = PublishSubject<[CLLocation]>()
internal lazy var didFailWithErrorSubject = PublishSubject<Error>()
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
_forwardToDelegate?.locationManager?(manager, didUpdateLocations: locations)
didUpdateLocationsSubject.onNext(locations)
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
_forwardToDelegate?.locationManager?(manager, didFailWithError: error)
didFailWithErrorSubject.onNext(error)
}

實際使用起來像這樣

public var didUpdateLocations: Observable<[CLLocation]> {
RxCLLocationManagerDelegateProxy.proxy(for: base).didUpdateLocationsSubject.asObservable()
}

另一種方式,使用methodInvoked來取的Observable,a即是[Any]型態,表示著didUpdateLocations的參數,以這裡來說,a[1]就代表locations: [CLLocation]

public var didUpdateLocations: Observable<[CLLocation]> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:)))
.map { a in
return try castOrThrow([CLLocation].self, a[1])
}
}

透過castOrThrow將a[1]轉成[CLLocation]型態,若不成功則拋出錯誤

private func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}

第七步 原本使用起來會像這樣

extension LocationDemoViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
viewModel.location.onNext(locations.last!)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
viewModel.currentAuthorizationStatus.onNext(status)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
viewModel.error.onNext(error)
}
}

經過Rx extension後,實際使用起來會像下面這樣,是不是更符合Rx了呢!

func bindViewModel() {
viewModel.locationSignal.bind(to: infoLabel.rx.text).disposed(by: disposeBag)
locationManager.rx.didUpdateLocations.map { $0.last! }.bind(to: viewModel.location).disposed(by: disposeBag)
locationManager.rx.didChangeAuthorizationStatus.bind(to: viewModel.currentAuthorizationStatus).disposed(by: disposeBag)
locationManager.rx.didFailWithError.bind(to: viewModel.error).disposed(by: disposeBag)
}

到此為止,對Delegate Rx化已經講完了,在這次研究DelegateProxy過程中,參考了許多文章,其中有一篇講得特別清楚,受到許多幫助,也分享給大家,RxSwift: How to make your favorite Delegate-based-APIs Reactive ?

在看Source code的過程中遇到許多困難,相對也學習到很多,大神們把程式變得很抽象,讓任何人都可以擴充自己的Rx extension。