對於一個很經常使用的兩個庫, MJRefresh 如何能夠像 UIButton 使用方式呢:react
btn.rx.tap.subscribe(...)
Rxswift 中的不少相似處理的方式都使用了跟下面極爲類似的代碼,git
UIControl
的適配時,是經過一箇中間層
ControlTarget
來完成的,爲了保持這個
ControlTarget
實例的存活,使得它不會被自動釋放,先用一個集合來包裹住它,並將這個集合設置爲目標
UIControl
的關聯對象。此時咱們能夠將這個中間層
ControlTarget
看作是這個事件流管道中的一個資源,這個資源的銷燬是由目標
UIControl
來決定的
我的寫的代碼以下:swift
import UIKit import MJRefresh import RxSwift import RxCocoa class RxTarget: NSObject, Disposable { // RxTarget 是 Rxswift 源碼 private var retainSelf: RxTarget? override init() { super.init() self.retainSelf = self } func dispose() { self.retainSelf = nil } } final class RefreshTarget<Component:MJRefreshComponent>: RxTarget { typealias Callback = MJRefreshComponentRefreshingBlock var callback: Callback? weak var component:Component? let selector = #selector(RefreshTarget.eventHandler) init(_ component: Component,callback:@escaping Callback) { self.callback = callback self.component = component super.init() component.setRefreshingTarget(self, refreshingAction: selector) } @objc func eventHandler() { if let callback = self.callback { callback() } } override func dispose() { super.dispose() self.component?.refreshingBlock = nil self.callback = nil } } extension Reactive where Base: MJRefreshComponent { var event: ControlEvent<Base> { let source: Observable<Base> = Observable.create { [weak control = self.base] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = control else { observer.on(.completed) return Disposables.create() } let observer = RefreshTarget(control) { observer.on(.next(control)) } return observer }.takeUntil(deallocated) return ControlEvent(events: source) } }
怎麼使用呢? api
collectionView.mj_header.rx.event .map { _ in Reactor.Action.refresh } .bind(to: reactor.action) .disposed(by: disposeBag) collectionView.mj_footer.rx.event .map { _ in Reactor.Action.loadMore } .bind(to: reactor.action) .disposed(by: disposeBag)
更多內容,請到個人 gitpageide