响应式编程(Reactive Programming,简称RP)
- 也是一种编程范式,于1997年提出,可以简化异步编程,提供更优雅的数据绑定
- 一般与函数式融合在一起,所以也会叫做:函数响应式编程(Functional Reactive Programming,简称FRP)
- 比较著名、成熟的响应式框架
-ReactiveCocoa
:简称RAC
,有Objective-C
、Swift
版本
&官网:http://reactivecocoa.io
&github:https://github.com/ReactiveCocoa
-ReactiveX
:简称Rx
,有众多编程语言的版本,比如RxKotlin
、RxJS
、RxCpp
、RxPHP
、RxGo
、RxSwift
等等
&官网:https://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上已有详细的安装教程,这里只演示CocoaPods方式的安装
1.Podfile
use_frameworks!
target 'target_name' do
pod 'RxSwift', '~> 5'
pod 'RxCocoa', '~> 5'
end
2.命令行
`pod repo update`
`pod install`
3.导入模块
import RxSwift
import RxCocoa
RxSwift的核心角色
- Observable:负责发送事件(Event)
-
Observer:负责订阅Observable,监听Observable发送的事件(Event)
- Event有3种
1. next:携带具体数据
2. error:携带错误信息,表明Observable终止,不会再发出事件
3.completed:表明Observable终止,不会再发出事件
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
}
创建、订阅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
switch event{
case .next(let element):
print("next",element)
case .error(let error):
print("error",error)
case .completed:
print("completed")
}
}
或者:
observable.subscribe(onNext: { element in
print("next", element)
}, onError: {error in
print("error", error)
}, onCompleted: {
print("completed")
})
创建、订阅Observable2
let observable = Observable<Int>.timer(.seconds(2),period:.seconds(1),scheduler:MainScheduler.instance)
2秒后每隔一秒钟在主线程发送一次事件
绑定到label上去:
observable.map{"数值是:\($0)"}.bind(to:label.rx.text)
Disposable
- 每当Observable被订阅时,都会返回一个Disposable实例,当调用Disposable的dispose,就相当于取消订阅
let disposable = observable.subscribe { event in
switch event{
case .next(let element):
print("next",element)
case .error(let error):
print("error",error)
case .completed:
print("completed")
}
}
disposable.dispose()
observable.subscribe { event in
switch event{
case .next(let element):
print("next",element)
case .error(let error):
print("error",error)
case .completed:
print("completed")
}
}.dispose()
只订阅一次,订阅完就取消了
- 在不需要再接收事件时,建议取消订阅,释放资源。有3种常见方式取消订阅
1、立即取消订阅(一次性订阅)
observable.subscribe { event in
print(event)
}.dispose()
2、当bag销毁(deinit)时,会自动调用Disposable实例的dispose(回收袋,自动释放池的感觉)
let bag = DisposeBag()
observable.subscribe { event in
print(event)
}.disposed(by:bag)
3、self销毁(deinit)时,会自动调用Disposable实例的dispose
let _ = observable.takeUntil(self.rx.deallocated).subscribe{ event in
print(event)
}
observable.subscribe(onNext: { element in
print("next", element)
}, onError: {error in
print("error", error)
}, onCompleted: {
print("completed")
},onDisposed:{
print("disposed")//dispose时的回调
}).dispose()
创建Observer
1、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()
2、Binder类型
let binder = Binder<String>(label) { label,text in
label.text = text
}
Observable.just(1).map{"数值是\($0)"}.subscribe(binder).dispose()
Observable.just(1).map{"数值是\($0)"}.bind(to:binder).dispose()
实例
button每隔一秒隐藏一次
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)