1、背景
響應(yīng)式編程(Reactive Programming仙辟,簡(jiǎn)稱RP)也是一種編程范式同波,于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/
github:https://github.com/ReactiveCocoa
ReactiveX(推薦)
簡(jiǎn)稱Rx吆玖,有眾多編程語言的版本筒溃,比如RxJava、RxKotlin沾乘、RxJS怜奖、RxCpp、RxPHP翅阵、RxGo歪玲、RxSwift等等
官網(wǎng): http://reactivex.io/
github: https://github.com/ReactiveX
2、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方式的安裝
Podfile
use_frameworks!
target 'target_name' do
pod 'RxSwift', '~> 5'
pod 'RxCocoa', '~> 5'
end
命令行
pod repo update
pod install
導(dǎo)入模塊
import RxSwift
import RxCocoa
模塊說明
RxSwift:Rx標(biāo)準(zhǔn)API的Swift實(shí)現(xiàn),不包括任何iOS相關(guān)的內(nèi)容
RxCocoa:基于RxSwift讹语,給iOS UI控件擴(kuò)展了很多Rx特性
3钙皮、RxSwift的核心角色
Observable:負(fù)責(zé)發(fā)送事件(Event)
Observer:負(fù)責(zé)訂閱Observable,監(jiān)聽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
}
4才菠、Disposable
每當(dāng)Observable被訂閱時(shí)茸时,都會(huì)返回一個(gè)Disposable實(shí)例,當(dāng)調(diào)用Disposable的dispose赋访,就相當(dāng)于取消訂閱
在不需要再接收事件時(shí)可都,建議取消訂閱缓待,釋放資源。有3種常見方式取消訂閱
1. 立即取消訂閱(一次性訂閱)
observable.subscribe { event in
print(event)
}.dispose()
2. 當(dāng)bag銷毀(deinit)時(shí)汹粤,會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
observable.subscribe { event in
print(event)
}.disposed(by: bag)
3. self銷毀時(shí)(deinit)時(shí)命斧,會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
let _ = observable.take(until: self.rx.deallocated).subscribe { event in
print(event)
}
5、創(chuàng)建嘱兼、訂閱Observable
/// 1.普通創(chuàng)建
var observable = Observable<Int>.create { observer in
observer.onNext(1)
observer.onCompleted()
return Disposables.create()
}
// 等價(jià)于
observable = Observable.just(1) //只能發(fā)送單個(gè)數(shù)據(jù)
observable = Observable.of(1) //可發(fā)送多個(gè)數(shù)據(jù)
observable = Observable.from([1])//可發(fā)送多個(gè)數(shù)據(jù)
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()
//等價(jià)于
let bag = DisposeBag()
observable.subscribe { event in
switch event {
case .next(let element):
print("next", element)
case .error(let error):
print("error",error)
case .completed:
print("completed")
}
}.disposed(by: bag)
/// 2.間隔時(shí)間發(fā)送, 比如: 兩秒之后, 每隔一秒鐘在主線程發(fā)送一次
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
//bind(to: 也是訂閱, 傳入?yún)?shù)為observer
let _ = observable
.take(until: self.rx.deallocated)
.map {"\($0)"}
.bind(to: UILabel().rx.text)//rx.text 是一個(gè)observer
6国葬、 創(chuàng)建Observer
//方式一: 通過AnyObserver
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()
//方式二: 通過Binder
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()
7、擴(kuò)展Binder屬性
/// 需求: 從兩秒后開始, 按鈕每隔1秒進(jìn)行一次顯隱切換
//方法一:
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
let binder = Binder<Bool>(button){ button, value in
button.isHidden = value
}
observable.map{ $0 % 2 == 0 }.bind(to: binder).disposed(by: bag)
//方法二:
let observable = Observable<Int>.timer(.seconds(2), period: .seconds(1), scheduler: MainScheduler.instance)
observable.map{ $0 % 2 == 0 }.bind(to: button.rx.hidden).disposed(by: bag) //要實(shí)現(xiàn)button.rx.hidden, 需要給button擴(kuò)展屬性
//擴(kuò)展Binder屬性: 來實(shí)現(xiàn)button.rx.hidden
extension Reactive where Base: UIView{
var hidden: Binder<Bool>{//只讀計(jì)算屬性
Binder<Bool>(base) { view, value in
view.isHidden = value
}
}
}
8芹壕、RxSwift的狀態(tài)監(jiān)聽
/// ①監(jiān)聽按鈕點(diǎn)擊狀態(tài)
button.rx.tap.subscribe(onNext: {
print("按鈕被點(diǎn)擊了1")
}).disposed(by: bag)
/// ②監(jiān)聽列表狀態(tài)
let data = Observable.just([
Person(name: "Jack", age: 10),
Person(name: "Rose", age: 20)
])
// 1.將數(shù)據(jù)綁定到TableView上
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)
// 2.TableViewCell點(diǎn)擊事件響應(yīng)
tableView.rx.modelSelected(Person.self)
.subscribe(onNext: { person in
print("點(diǎn)擊了", person.name)
}).disposed(by: bag)
/// ③監(jiān)聽對(duì)象屬性變化(類似KVO)
class Dog: NSObject {
//@objc dynamic應(yīng)用于變量是為了讓變量能夠使用kvo機(jī)制
@objc dynamic var name: String?
}
let dog = Dog()
let bag = DisposeBag()
dog.rx.observe(String.self, "name")
.subscribe(onNext: { name in
print("name is", name ?? "nil")
}).disposed(by: bag)
dog.name = "Kris"
dog.name = "Amok"
/// ④監(jiān)聽通知
NotificationCenter.default.rx
.notification(UIApplication.didEnterBackgroundNotification)
.subscribe(onNext: { notification in
print("APP進(jìn)入后臺(tái)", notification)
}).disposed(by: bag)
9汇四、既是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)
// 總結(jié): 諸如UISlider.rx.value踢涌、UTextField.rx.text這類屬性值通孽,既是Observable,又是Observer
// 它們是RxCocoa.ControlProperty類型