作为一个iOS开发者,Swift语言已经成为了标配,要想在苹果生态里生存下去,不得不掌握这门语言。
Rx家族是一个非常牛逼的家族,相信是个程序员都知道这个家族,从今天开始,慢慢的更新文章,带着大家一起小试牛刀一下RxSwift。
通过几个例子 体现一下RxSwift的逼格有多高
------Button
添加事件:
button.addTarget(self, action:#selector(clickButton) , for: .touchUpInside)
实现事件:
@objc func clickButton(){
print("点了按钮")
}
直接用RxSwift来实现:
button.rx.tap
.subscribe(onNext: { [weak self]() in
print("进来了")
}, onError: nil, onCompleted: nil)
.disposed(by: disposeBag)
默认就是实现touchUpInside事件,如果是想实现其他事件,举例touchUpOutside事件:
button.rx.controlEvent(.touchUpOutside)
.subscribe(onNext: { () in
print("点击了按钮外面")
})
.disposed(by: disposeBag)
------UITextField
原生的如果想监听某个textField变化后赋值给其他控件,比较繁琐,需要实现textField的代理事件等方法,下面看下RxSwift如何简单方便的实现
textField.rx.text.orEmpty
.subscribe(onNext: { [weak self](text) in
self?.showLabel.text=text
})
.disposed(by: disposeBag)
甚至可以更简练:
textField.rx.text
.bind(to: self.showLabel.rx.text)
.disposed(by: disposeBag)
------KVO
原生的代码就像下面如此的繁琐,如果发现监听不到,Swift里面需要监听的属性需要这样:
@objc dynamic var name:String="小狗" //添加 @objc dynamic 前缀
// 添加监听的key
self.animal.addObserver(self, forKeyPath: "name", options: .new, context: nil)
// 监听的值变化的回调
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("监听到变化了")
print(change as Any)
}
// 释放
deinit {
self.removeObserver(self.animal, forKeyPath: "name", context: nil)
}
如果使用RxSwift看看有多么简单粗暴,原来需要写在3个地方的代码,全部一个闭包搞定!!!
self.animal.rx.observeWeakly(String.self, "name")
.subscribe(onNext: { (value) in
print(value as Any)
})
.disposed(by: disposeBag)
举了这几个例子,是不是发现如果使用RxSwift会上瘾!!!
如何做到万物皆Rx的...
点进去直接看源码:
/// A type that has reactive extensions.
public protocol ReactiveCompatible {
/// Extended type
associatedtype ReactiveBase
@available(*, deprecated, message: "Use `ReactiveBase` instead.")
typealias CompatibleType = Self.ReactiveBase
/// Reactive extensions.
static var rx: RxSwift.Reactive.Type { get set }
/// Reactive extensions.
var rx: RxSwift.Reactive { get set }
}
直接来到最后几行:
/// Extend NSObject with `rx` proxy.
extension NSObject : ReactiveCompatible {
}
NSObject遵循了ReactiveCompatible协议,所以NSObject及其子类都可以 .rx ...而NSObject又是基类所以万物皆Rx了。
// UI -> target - event
// 1:创建序列
// AnonymousObservable -> producer.subscriber -> run
// 保存闭包 - 函数式 保存 _subscribeHandler
//
let ob = Observable.create { (obserber) -> Disposable in
// 3:发送信号
obserber.onNext("Box走起")
obserber.onCompleted()
obserber.onError(NSError.init(domain: "boxError", code: 10086, userInfo: nil))
return Disposables.create()
}
// 2:订阅信号
// AnonymousObserver - event .next -> onNext()
// _eventHandler
// AnonymousObservable._subscribeHandler(observer)
// 销毁
let _ = ob.subscribe(onNext: { (text) in
print("订阅到:\(text)")
}, onError: { (error) in
print("error: \(error)")
}, onCompleted: {
print("完成")
}) {
print("销毁")
}
这是一个简单的序列产生和订阅的过程。
Observable实质上就是一个Sequence。序列分为有穷序列和无穷序列,主要就是用来形成一条数据流。我们所有的操作产生的数据都会通过Observable传输。Observable
final private class AnonymousObservable: Producer {
typealias SubscribeHandler = (AnyObserver) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
}
final private class AnonymousObservableSink: Sink, ObserverType {
typealias Element = Observer.Element
typealias Parent = AnonymousObservable
// state
private let _isStopped = AtomicInt(0)
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
switch event {
case .next:
if load(self._isStopped) == 1 {
return
}
self.forwardOn(event)
case .error, .completed:
if fetchOr(self._isStopped, 1) == 0 {
self.forwardOn(event)
self.dispose()
}
}
}
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
返回了一个AnonymousObservable类。在AnonymousObservable源码里可以看到创建了保存了回调的序列AnonymousObservable。
- 当序列被订阅的时候会调用父类Producer的subscribe方法
- 调用self的run方法
- 创建AnonymousObservableSink同时将订阅者observer传进去
- 调用AnonymousObservableSink实例的run
- 调用AnonymousObservable的_subscribeHandler闭包,参数就是保存了所有事件的observer