1.響應式編程
響應式編程(Reactive Programming,簡稱RP), 也是一種編程范式悬槽,于1997年提出,可以簡化異步編程瞬浓,提供更優(yōu)雅的數(shù)據(jù)綁定初婆, 一般與函數(shù)式融合在一起,所以也會叫做:函數(shù)響應式編程(Functional Reactive Programming猿棉,簡稱FRP)
- 比較著名的磅叛、成熟的響應式框架:
-
ReactiveCocoa
- 簡稱RAC,有Objective-C铺根、Swift版本
- 官網(wǎng): http://reactivecocoa.io/
- github:https://github.com/ReactiveCocoa
-
ReactiveX
簡稱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版本
-
模塊說明
- RxSwift:Rx標準API的Swift實現(xiàn)精置,不包括任何iOS相關的內(nèi)容
-
RxCocoa:基于RxSwift,給iOS UI控件擴展了很多Rx特性
-
RxSwift的核心角色
- Observable:負責發(fā)送事件(Event)
-
Observer:負責訂閱Observable锣杂,監(jiān)聽Observable發(fā)送的事件(Event)
-
Event有3種
- next:攜帶具體數(shù)據(jù)
- error:攜帶錯誤信息脂倦,表明Observable終止,不會再發(fā)出事件
- completed:表明Observable終止元莫,不會再發(fā)出事件
2.1 創(chuàng)建赖阻、訂閱Observable1
/*
var observable = Observable<Int>.create { observer in
observer.onNext(1)
observer.onCompleted()
return Disposables.create()
}
// 等價于
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()
}
// 等價于
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()
2.2 創(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)
/// range
// Observable.range(start: 2, count: 10)
// .subscribe { (event : Event<Int>) in
// print(event)
// }.dispose()
/// repeatElement
// Observable.repeatElement("hello")
// .take(4)
// .subscribe { (event) in
// print(event)
// }.dispose()
2.3 創(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()
2.4 擴展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)
2.5 傳統(tǒng)的狀態(tài)監(jiān)聽
在開發(fā)中經(jīng)常要對各種狀態(tài)進行監(jiān)聽踱蠢,傳統(tǒng)的常見監(jiān)聽方案有
- KVO
- Target-Action
- Notification
- Delegate
- Block Callback
傳統(tǒng)方案經(jīng)常會出現(xiàn)錯綜復雜的依賴關系火欧、耦合性較高,還需要編寫重復的非業(yè)務代碼
2.6 RxSwift的狀態(tài)監(jiān)聽1
button.rx.tap
.subscribe(onNext: {
print("按鈕被點擊了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("點擊了", person.name)
}).disposed(by: bag)
2.7 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進入后臺", notification)
}).disposed(by: bag)
2.8 既是Observable,又是Observer
Observable.just(0.8).bind(to: slider.rx.value).dispose()
slider.rx.value.map {
"當前數(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類型
2.9 Disposable
- 每當Observable被訂閱時榆浓,都會返回一個Disposable實例于未,當調(diào)用Disposable的dispose,就相當于取消訂閱
- 在不需要再接收事件時哀军,建議取消訂閱沉眶,釋放資源。有3種常見方式取消訂閱
- 立即取消訂閱(一次性訂閱)
observable.subscribe { event in
print(event)
}.dispose()
// 當bag銷毀(deinit)時杉适,會自動調(diào)用Disposable實例的dispose
observable.subscribe { event in
print(event)
}.disposed(by: bag)
// self銷毀時(deinit)時谎倔,會自動調(diào)用Disposable實例的dispose
let _ = observable.takeUntil(self.rx.deallocated).subscribe { event in
print(event)
}
2.10 PublishSubject、ReplaySubject猿推、BehaviorSubject片习、Variable
/// 四種序列
///1. PublishSubject, 訂閱者只能接受,訂閱之后發(fā)出的事件
//let publishSub = PublishSubject<String>()
//不會接收到
//publishSub.onNext("coderwhy")
//publishSub.subscribe { (event : Event<String>) in
// print(event)
//}.disposed(by: bag)
//會接收到
//publishSub.onNext("coderwhy")
///2蹬叭、ReplaySubject, 訂閱者可以接受訂閱之前的事件&訂閱之后的事件
//let replaySub = ReplaySubject<String>.create(bufferSize: 4)
//replaySub.onNext("a")
//replaySub.onNext("b")
//replaySub.onNext("c")
//replaySub.onNext("d")
//replaySub.onNext("e")
//
//replaySub.subscribe { (event) in
// print(event)
//}.disposed(by: bag)
//replaySub.onNext("f")
//3藕咏、BehaviorSubject, 訂閱者可以接受,訂閱之前的最后一個事件
//let behaviorSub = BehaviorSubject(value: "a")
//behaviorSub.onNext("b")
//behaviorSub.onNext("c")
//behaviorSub.onNext("d")
//
//behaviorSub.subscribe { (event : Event<String>) in
// print(event)
//}.disposed(by: bag)
//
//behaviorSub.onNext("e")
//behaviorSub.onNext("f")
//behaviorSub.onNext("g")
///4秽五、Variable,
///1孽查、相當于對BehaviorSubject進行裝箱
///2、如果想將Variable當成Observable坦喘,讓訂閱者進行訂閱時盲再,需要asObservable轉(zhuǎn)成Observable
///3、如果Variable打算發(fā)出事件瓣铣,直接修改對象的value即可
///4答朋、當事件結(jié)束時,Variable會自動發(fā)出completed事件
//let variable = Variable("a")
//variable.value = "1"
//variable.asObservable().subscribe { (event : Event<String>) in
// print(event)
//}.disposed(by: bag)
//variable.value = "2"
//: map flatMap使用
/// map
Observable.of(1,2,3,4).map { (value) -> Int in
return value * value
}
.subscribe { (event : Event<Int>) in
print(event)
}
.disposed(by: bag)
/// flatMap使用
struct Student {
var score : Variable<Double>
}
let stu1 = Student(score: Variable(80))
let stu2 = Student(score: Variable(100))
let studentVariable = Variable(stu1)
studentVariable.asObservable()
.flatMapLatest({ (stu : Student) -> Observable<Double> in
return stu.score.asObservable()
})
// .flatMap { (stu : Student) -> Observable<Double> in
// return stu.score.asObservable()
// }
.subscribe { (event : Event<Double>) in
print(event.element as Any)
}.disposed(by: bag)
studentVariable.value = stu2
stu1.score.value = 1999
*/