響應(yīng)式編程
響應(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/ReactiveCocoaReactiveX
簡(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方式的安裝
① 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
- 模塊說(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ā)送事件(Event)
- Observer:負(fù)責(zé)訂閱Observable晤锥,監(jiān)聽Observable發(fā)送的事件(Event)
發(fā)出事件為枚舉實(shí)例:
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
}
Event有3種:
- next:攜帶具體數(shù)據(jù)
- error:攜帶錯(cuò)誤信息掉蔬,表明Observable終止,不會(huì)再發(fā)出事件
- completed:表明Observable終止矾瘾,不會(huì)再發(fā)出事件
創(chuàng)建女轿、訂閱Observable
- 發(fā)送一個(gè)事件
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])
- 發(fā)送多個(gè)事件
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)建定時(shí)器
//參數(shù)1: 延遲時(shí)間, period:間隔時(shí)間, scheduler: 執(zhí)行線程
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
- 1>AnyObserver 創(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()
- 2> Binder 創(chuàng)建Observer
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)聽
在開發(fā)中經(jīng)常要對(duì)各種狀態(tài)進(jìn)行監(jiān)聽,傳統(tǒng)的常見監(jiān)聽方案有
- KVO
- Target-Action
- Notification
- Delegate
- Block Callback
傳統(tǒng)方案經(jīng)常會(huì)出現(xiàn)錯(cuò)綜復(fù)雜的依賴關(guān)系壕翩、耦合性較高蛉迹,還需要編寫重復(fù)的非業(yè)務(wù)代碼
RxSwift的狀態(tài)監(jiān)聽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)聽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種常見方式取消訂閱
1> 立即取消訂閱(一次性訂閱)
observable.subscribe { event in
print(event)
}.dispose()
2> 當(dāng)bag銷毀(deinit)時(shí),會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
let bag = DisposeBag()
observable.subscribe { event in
print(event)
}.disposed(by: bag)
3> self銷毀時(shí)(deinit)時(shí)蹭劈,會(huì)自動(dòng)調(diào)用Disposable實(shí)例的dispose
let _ = observable.takeUntil(self.rx.deallocated).subscribe { event in
print(event)
}