RxSwift
RxSwift簡介
RxSwift 是 ReactiveX 家族的重要一員, ReactiveX 是 Reactive Extensions 的縮寫卓研,一般簡寫為Rx珠插。ReactiveX 官方給Rx的定義是,Rx是一個使用可觀察數(shù)據(jù)流進行異步編程的編程接口洼裤。
ReactiveX 不僅僅是一個編程接口蓬坡,它是一種編程思想的突破骏啰,它影響了許多其它的程序庫和框架以及編程語言。它拓展了觀察者模式奕剃,使你能夠自由組合多個異步事件栋齿,而不需要去關心線程亚兄,同步,線程安全,并發(fā)數(shù)據(jù)以及I/O阻塞监徘。
RxSwift 是 Rx 為 Swift 語言開發(fā)的一門函數(shù)響應式編程語言桥狡, 它可以代替iOS系統(tǒng)的 Target Action / 代理 / 閉包 / 通知 / KVO 等等详瑞,同時還提供網絡请毛、數(shù)據(jù)綁定、UI事件處理聂薪、UI的展示和更新家乘、多線程等等。
函數(shù)響應式編程
*和指令式編程相比藏澳,函數(shù)式編程強調函數(shù)的計算比指令的執(zhí)行重要仁锯。
*和過程化編程相比,函數(shù)式編程里函數(shù)的計算可隨時調用翔悠。
- RxSwift優(yōu)勢
- swift為值類型业崖,在傳值與方法回調上有影響,RxSwift一定程度上彌補swift的靈活性
- RxSwift使得代碼復用性較強蓄愁,減少代碼量
- RxSwift因為聲明都是不可變更双炕,增加代碼可讀性
- RxSwift使得更易于理解業(yè)務代碼,抽象異步編程撮抓,統(tǒng)一代碼風格
- RxSwift使得代碼更易于編寫集成單元測試妇斤,增加代碼穩(wěn)定性
RxSwift簡單使用
- RxSwift-網絡請求
//MARK: - RxSwift應用-網絡請求
func setupNextwork() {
let url = URL(string: "https://www.baidu.com")
URLSession.shared.rx.response(request: URLRequest(url: url!))
.subscribe(onNext: { (response,data) in
print(response)
}).disposed(by: disposeBag)
}
- RxSwift-timer定時器
//MARK: - RxSwift應用-timer定時器
func setupTimer() {
timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
print(num)
})
.disposed(by: disposeBag)
}
- RxSwift-通知
//MARK: - 通知
func setupNotification(){
NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
.subscribe(onNext: { (noti) in
print(noti)
})
.disposed(by: disposeBag)
}
- RxSwift-手勢
//MARK: - 手勢
func setupGestureRecognizer(){
let tap = UITapGestureRecognizer()
self.label.addGestureRecognizer(tap)
self.label.isUserInteractionEnabled = true
tap.rx.event.subscribe(onNext: { (tap) in
print(tap.view)
})
.disposed(by: disposeBag)
}
- RxSwift-UIScrollView
//MARK: - RxSwift應用-scrollView
func setupScrollerView() {
scrollView.rx.contentOffset
.subscribe(onNext: { [weak self](content) in
self?.view.backgroundColor = UIColor.init(red: content.y/255*0.8, green: content.y/255*0.6, blue: content.y/255*0.3, alpha: 1)
})
.disposed(by: disposeBag)
}
- RxSwift-UITextFiled
//MARK: - RxSwift應用-textfiled
func setupTextFiled() {
self.textFiled.rx.text.orEmpty
.subscribe(onNext: { (text) in
print(text)
})
.disposed(by: disposeBag)
}
- RxSwift-UIButton
//MARK: - RxSwift應用-button響應
func setupButton() {
self.button.rx.tap
.subscribe(onNext: { () in
print("點擊來了")
})
.disposed(by: disposeBag)
}
- RxSwift-KVO
//MARK: - RxSwift應用-KVO
func setupKVO() {
self.person.rx.observeWeakly(String.self, "name")
.subscribe(onNext: { (value) in
print(value as Any)
})
.disposed(by: disposeBag)
}
RxSwift核心邏輯
-
RxSwift核心流程大致分為:
1.創(chuàng)建序列:create
2.訂閱序列:subscribe
3.發(fā)送信號:onNext
let ob = Observable<Any>.create { (obserber) -> Disposable in
// 3:發(fā)送信號
obserber.onNext("御雪飛斐")
obserber.onCompleted()
//obserber.onError(NSError.init(domain: "coocieeror", code: 10087, userInfo: nil))
return Disposables.create()
}
let _ = ob.subscribe(onNext: { (text) in
print("訂閱到:\(text)")
}, onError: { (error) in
print("error: \(error)")
}, onCompleted: {
print("完成")
}) {
print("銷毀")
}
-
核心邏輯分解:
創(chuàng)建序列
extension ObservableType {
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
}
final private class AnonymousObservableSink<O: ObserverType>: Sink<O>, ObserverType {
...
...
func run(_ parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
- AnonymousObservable 具體實現(xiàn)run
final private class AnonymousObservable<Element>: Producer<Element> {
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AnonymousObservableSink(observer: observer, cancel: cancel)
let subscription = sink.run(self)
return (sink: sink, subscription: subscription)
}
}
- 繼承關系如下 AnonymousObservable -> Producer -> Observable -> ObservableType
- ObservableType協(xié)議中定義的subscribe方法由Producer實現(xiàn),具體實現(xiàn)有Producer的子類實現(xiàn)
- 重點代碼 let sinkAndSubscription = self.run(observer, cancel: disposer)
class Producer<Element> : Observable<Element> {
...
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
...
// The returned disposable needs to release all references once it was disposed.
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
...
}
}
- Observable
public class Observable<Element> : ObservableType {
.....
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
rxAbstractMethod()
}
.....
}
下面這個方法會在訂閱中調用:
public func asObservable() -> Observable<E> {
return self
}
訂閱序列subscribe
- 調用subscribe創(chuàng)建 AnonymousObserver;
- AnonymousObserver保存外部的eventHandler站超;
- subscribe中的Disposables調用self.asObservable().subscribe(observer)時荸恕,走上面的AnonymousObservable調用父類Producer的subscribe實現(xiàn)流程
extension ObservableType {
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
.....
let observer = AnonymousObserver<E> { event in
......
switch event {
case .next(let value):
onNext?(value)
case .error(let error):
if let onError = onError {
onError(error)
}
else {
Hooks.defaultErrorHandler(callStack, error)
}
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.asObservable().subscribe(observer),
disposable
)
}
}
- AnonymousObserver
final class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
typealias Element = ElementType
typealias EventHandler = (Event<Element>) -> Void
private let _eventHandler : EventHandler
init(_ eventHandler: @escaping EventHandler) {
....
self._eventHandler = eventHandler
}
override func onCore(_ event: Event<Element>) {
return self._eventHandler(event)
}
.....
}
onNext信號事件
- 在Controller的代碼中:
let ob = Observable<Any>.create { (obserber) -> Disposable in
// 3:發(fā)送信號
obserber.onNext("發(fā)送信號")
return Disposables.create()
}
- 最終調用到:
extension ObserverType {
public func onNext(_ element: E) {
self.on(.next(element))
}
.......
}
- 具體實現(xiàn):
關鍵代碼 ** public func on(_ event: Event<Element>)**
public struct AnyObserver<Element> : ObserverType {
......
public init<O : ObserverType>(_ observer: O) where O.E == Element {
self.observer = observer.on
}
public func on(_ event: Event<Element>) {
return self.observer(event)
}
.....
}
整個RxSwift流程如下: