函数式编程
- 响应式编程(Reactive Programming,简称 RP)
- 也是一种范式编程
- 一般与函数式融合一起,所以也叫函数响应式编程(Functiona Reactive Programming,简称 FRP)
ReactiveX
- 有很多种编程语言,如RxJava RxSwift...
- 安装
# Podfile use_frameworks! target 'YOUR_TARGET_NAME' do pod 'RxSwift', '~> 5' pod 'RxCocoa', '~> 5' end # RxTest and RxBlocking make the most sense in the context of unit/integration tests target 'YOUR_TESTING_TARGET' do pod 'RxBlocking', '~> 5' pod 'RxTest', '~> 5' end
RxSwift 核心角色
Observable: 负责发送实践的 (Event)
-
Observer: 负责订阅 Observable ,监听 Observable 发送的事件(Event)
public enum Event<Element> { case next(Element) ` 携带数据 ` case error(Swift.Error) `遵守 swift error 协议,后面消息不发送` case completed ` 观察者终止行动 ` }
Observable 发布消息
- 代码
let obs = Observable<Int>.create{ observer in observer.onNext(11) observer.onNext(22) observer.onNext(33) observer.onCompleted() `完成监听` return Disposables.create() }
subscribe 监听消息
- 代码
import RxCocoa import RxSwift let bag = DisposeBag() // 回收袋 //第一种方法 obs.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) } // 第二种方法 obs.subscribe(onNext: { (element) in print("next", element) }, onError: { (error) in print("error", error) }, onCompleted: { print("completed") }) // 定时器功能 let obs = Observable<Int>.timer(.seconds(3), period: .seconds(5), scheduler: MainScheduler.instance) // 3 秒后启动定时器,每间隔 5 秒,在 主线程上发一次消息
Disposable 释放 obs
每当 Observable 被订阅时,都会返回一个 Disposable 实例,当调用 Disposable 的 dispose , 就相当于取消订阅
-
在不需要再接收事件时,建议取消订阅,释放资源,常见有三种取消订阅方式
// 第一种 obs.subscribe { event in // do something }.dispose() //立即取消订阅 // 第二种, obs.subscribe { event in // do something }.dispose(by: bag) //bag 回收袋,controller 销毁, bag 销毁,obs 调用取消订阅接口 //第三种 obs .takeUntil(self.rx.deallocated) //直到 控制器调用 deallocated 方法,取消订阅 .subscribe { event in // do something }
创建 Observer
-
通过 AnyObserver 类型创建 obs
let obs = AnyObserver<Int>.init { event in switch event { case .next(let element): print("next", element) case .error(let error): print("error", error) case .completed: print("completed") } } // 只调用一次,发送消息内容为 5 Observable.just(5).subscribe(obs).dispose()
-
通过 Observable 类型创建 obs
let obs = Observable<Int>.create{ observer in observer.onNext(33) observer.onCompleted() return Disposables.create() } //监听 obs.subscribe(onNext: { (element) in print("next", element) }, onError: { (error) in print("error", error) }, onCompleted: { print("completed") }).disposed(by: bag) obs.subscribe { event in switch event { case .next(let element): print("next", element) case .error(let error): print("error", error) case .completed: print("completed") } }.dispose()
-
通过 bind 创建
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()