響應(yīng)式編程
- 響應(yīng)式編程
也是一種編程范式蜘渣,于1997年提出授舟,可以簡(jiǎn)化異步編程塞弊,提供更優(yōu)雅的數(shù)據(jù)綁定
一般與函數(shù)式融合在一起,所以也會(huì)叫做函數(shù)響應(yīng)式編程(Functional Reactive Programming强窖,簡(jiǎn)稱FRP)
- 比較著名的凸椿、成熟的響應(yīng)式框架
ReactiveCocoa
簡(jiǎn)稱RAC,有Objective-C翅溺、Swift版本
官網(wǎng): http://reactivecocoa.io/
ReactiveX
簡(jiǎn)稱Rx脑漫,有眾多編程語(yǔ)言的版本,比如RxJava咙崎、RxKotlin优幸、RxJS、RxCpp叙凡、RxPHP劈伴、RxGo、RxSwift等等
官網(wǎng): http://reactivex.io/
github: https://github.com/ReactiveX
RxSwift
- RxSwift(ReactiveX for Swift)握爷,ReactiveX的Swift版本
源碼:https://github.com/ReactiveX/RxSwift
中文文檔: https://beeth0ven.github.io/RxSwift-Chinese-Documentation/
-
RxSwift的github上已經(jīng)有詳細(xì)的安裝教程,這里只演示CocoaPods方式的安裝
模塊說(shuō)明
RxSwift:Rx標(biāo)準(zhǔn)API的Swift實(shí)現(xiàn)严里,不包括任何iOS相關(guān)的內(nèi)容
RxCocoa:基于RxSwift新啼,給iOS UI控件擴(kuò)展了很多Rx特性
RxSwift的核心角色
Observable:負(fù)責(zé)發(fā)送時(shí)間(Event)
-
Observer:負(fù)責(zé)訂閱Observable,監(jiān)聽(tīng)Observable發(fā)送的事件(Event)
Event有3種
next:攜帶具體數(shù)據(jù)
error:攜帶錯(cuò)誤信息刹碾,表明Observable終止燥撞,不會(huì)再發(fā)出事件
completed:表明Observable終止,不會(huì)再發(fā)出事件
public enum Event<Element> {
/// Next element is produced.
case next(Element)
/// Sequence terminated with an error.
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
創(chuàng)建、訂閱Observable1
var observable = Observable<Int>.create { observer in
observer.onNext(1)
observer.onCompleted()
return Disposables.create()
}
// 等價(jià)于
observable = Observable.just(1)
observable = Observable.of(1)
observable = Observable.from([1])
var observable = Observable<Int>.create { observer in
observer.onNext(1)
observer.onNext(2)
observer.onNext(3)
observer.onCompleted()
return Disposables.create()
}
// 等價(jià)于
observable = Observable.of(1, 2, 3)
observable = Observable.from([1, 2, 3])
observable.subscribe { event in
print(event)
}.dispose()
observable.subscribe(onNext: {
print("next", $0)
}, onError: {
print("error", $0)
}, onCompleted: {
print("completed")
}, onDisposed: {
print("dispose")
}).dispose()
創(chuàng)建物舒、訂閱Observable2
let observable = Observable<Int>.timer(.seconds(3),
period: .seconds(1),
scheduler: MainScheduler.instance)
observable.map { "數(shù)值是\($0)" }
.bind(to: label.rx.text)
.disposed(by: bag)
創(chuàng)建Observer
let observer = AnyObserver<Int>.init { event in
switch event {
case .next(let data):
print(data)
case .completed:
print("completed")
case .error(let error):
print("error", error)
}
}
Observable.just(1).subscribe(observer).dispose()
let binder = Binder<String>(label) { label, text in
label.text = text
}
Observable.just(1).map { "數(shù)值是\($0)" }.subscribe(binder).dispose()
Observable.just(1).map { "數(shù)值是\($0)" }.bind(to: binder).dispose()
擴(kuò)展Binder屬性
extension Reactive where Base: UIView {
var hidden: Binder<Bool> {
Binder<Bool>(base) { view, value in
view.isHidden = value
}
}
}
let observable = Observable<Int>.interval(.seconds(1),
scheduler: MainScheduler.instance)
observable.map { $0 % 2 == 0 }.bind(to: button.rx.hidden).disposed(by: bag)
傳統(tǒng)的狀態(tài)監(jiān)聽(tīng)
- 在開(kāi)發(fā)中經(jīng)常要對(duì)各種狀態(tài)進(jìn)行監(jiān)聽(tīng)色洞,傳統(tǒng)的常見(jiàn)監(jiān)聽(tīng)方案有
KVO
Target-Action
Notification
Delegate
Block Callback
- 傳統(tǒng)方案經(jīng)常會(huì)出現(xiàn)錯(cuò)綜復(fù)雜的依賴關(guān)系、耦合性較高冠胯、還需要編寫(xiě)重復(fù)的非業(yè)務(wù)代碼
RxSwift的狀態(tài)監(jiān)聽(tīng)1
button.rx.tap.subscribe(onNext: {
print("按鈕被點(diǎn)擊了1")
}).disposed(by: bag)
let data = Observable.just([
Person(name: "Jack", age: 10),
Person(name: "Rose", age: 20)
])
data.bind(to: tableView.rx.items(cellIdentifier: "cell")) { row, person, cell in
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = "\(person.age)"
}.disposed(by: bag)
tableView.rx.modelSelected(Person.self)
.subscribe(onNext: { person in
print("點(diǎn)擊了", person.name)
}).disposed(by: bag)
RxSwift的狀態(tài)監(jiān)聽(tīng)2
class Dog: NSObject {
@objc dynamic var name: String?
}
dog.rx.observe(String.self, "name")
.subscribe(onNext: { name in
print("name is", name ?? "nil")
}).disposed(by: bag)
dog.name = "larry"
dog.name = "wangwang"
NotificationCenter.default.rx
.notification(UIApplication.didEnterBackgroundNotification)
.subscribe(onNext: { notification in
print("APP進(jìn)入后臺(tái)", notification)
}).disposed(by: bag)
既是Observable火诸,又是Observer
Observable.just(0.8).bind(to: slider.rx.value).dispose()
slider.rx.value.map {
"當(dāng)前數(shù)值是:\($0)"
}.bind(to: textField.rx.text).disposed(by: bag)
textField.rx.text
.subscribe(onNext: { text in
print("text is", text ?? "nil")
}).disposed(by: bag)
- 諸如UISlider.rx.value、UTextField.rx.text這類屬性值荠察,既是Observable置蜀,又是Observer
它們是RxCocoa.ControlProperty類型
Disposable
每當(dāng)Observable被訂閱時(shí),都會(huì)返回一個(gè)Disposable實(shí)例悉盆,當(dāng)調(diào)用Disposable的dispose盯荤,就相當(dāng)于取消訂閱
在不需要再接收事件時(shí),建議取消訂閱焕盟,釋放資源秋秤。有3種常見(jiàn)方式取消訂閱
// 立即取消訂閱(一次性訂閱)
observable.subscribe { event in
print(event)
}.dispose()
// 當(dāng)bag銷毀(deinit)時(shí),會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
observable.subscribe { event in
print(event)
}.disposed(by: bag)
// self銷毀時(shí)(deinit)時(shí)脚翘,會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
let _ = observable.takeUntil(self.rx.deallocated).subscribe { event in
print(event)
}