Swift5.1语法学习

二十二、响应式编程

2020-02-26  本文已影响0人  爱玩游戏的iOS菜鸟

响应式编程

响应式编程(Reactive Programming,简称RP),也是一种编程范式,于1997年提出,可以简化异步编程,提供更优雅的数据绑定。

一般与函数式融合在一起,所以也会叫做:函数响应式编程(Functional Reactive Programming,简称FRP)。

响应式框架

RxSwift安装及使用

use_frameworks!

target 'target_name' do
  pod 'RxSwift', '~> 5'
  pod 'RxCocoa', '~> 5'
end
import RxSwift
import RxCocoa

RxSwift:Rx标准API的Swift实现,不包括任何iOS相关的内容
RxCocoa:基于RxSwift,给iOS的UI控件扩展了很多Rx特性

RxSwift的核心角色

Event有3种:

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
}

创建、订阅Observable

  1. 创建Observable:
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]) //如果接受的是数组,就把数组元素一个一个发出去
  1. 订阅Observable(接收消息)
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() //订阅完之后⻢上取消订阅,只订阅⼀次

//上面写法和下面等价:
observable.subscribe(onNext: { //传个闭包表达式来订阅
    print("next", $0)
}, onError: {
    print("error", $0)
}, onCompleted: {
    print("completed")
}, onDisposed: {
    print("dispose")
}).dispose() //订阅完之后⻢上取消订阅,只订阅⼀次

根据如下例子,理解of和from的区别:

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]) //数组,发三次
  1. 取消订阅(Disposable)
//立即取消订阅(一次性订阅)
observable.subscribe { event in
    print(event)
}.dispose()

//当bag销毁(deinit)时,会自动调用Disposable实例的dispose
observable.subscribe { event in
    print(event)
}.disposed(by: bag)

//self销毁时(deinit)时,会自动调用Disposable实例的dispose
//takeUntil是保留到什么时候的意思
let _ = observable.takeUntil(self.rx.deallocated).subscribe { event in
    print(event)
}

创建Observer

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()
Binder:
//Binder内部也有⼀个Observer,绑定⼀个就相当于订阅了
let binder = Binder<String>(label) { label, text in
    label.text = text
}

//将"数值是1"绑定到label.text上
Observable.just(1).map { "数值是\($0)" }.subscribe(binder).dispose()
//等价于下面
Observable.just(1).map { "数值是\($0)" }.bind(to: binder).dispose()

使用定时器让button每隔1秒钟隐藏、显示一次,如下:

//创建Observable
//2秒之后,每隔1秒钟在主线程发消息 
let observable = Observable<Int>.timer(.second(2)), period: .second(1), scheduler: MainScheduler.instance)
let binder = Binder<BOOL>(button) { button, value in
    button.isHidden = value
}
//订阅Observable 
//bind内部其实就是订阅
observable.map { $0 % 2 == 0 }.bind(to: binder).disposed(by: bag) //int转Bool

上面是把 0 % 2 == 0 绑定到binder上面,那么能不能把0 % 2 == 0 绑定到button.rx.hidden上面呢?

//给UIView扩展hidden属性
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)

状态监听

传统的状态监听

传统的常见监听方案有:

RxSwift的状态监听
button:
//订阅button的点击事件
button.rx.tap.subscribe(onNext: {
    print("按钮被点击了1")
}).disposed(by: bag)
tableview:
let data = Observable.just([
    Person(name: "Jack", age: 10),
    Person(name: "Rose", age: 20)
])
//数据源绑定到tableview上,数据源改变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)
cell:
//订阅cell的点击⽅法
tableView.rx.modelSelected(Person.self)
    .subscribe(onNext: { person in
        print("点击了", person.name)
    }).disposed(by: bag)
属性:
class Dog: NSObject {
    @objc dynamic var name: String?
}
//Rx形式的KVO监听属性
dog.rx.observe(String.self, "name")
    .subscribe(onNext: { name in
        print("name is", name ?? "nil")
    }).disposed(by: bag)
dog.name = "larry"
dog.name = "wangwang"
通知:
//Rx形式的通知监听
NotificationCenter.default.rx
    .notification(UIApplication.didEnterBackgroundNotification)
    .subscribe(onNext: { notification in
        print("APP进入后台", notification)
    }).disposed(by: bag)

既是Observable,又是Observer

//slider.rx.value是接收者
Observable.just(0.8).bind(to: slider.rx.value).dispose()

//现在slider.rx.value是发送者,textField.rx.text是接受者
slider.rx.value.map {
    "当前数值是:\($0)"
}.bind(to: textField.rx.text).disposed(by: bag)

//现在textField.rx.text是发送者,然后再订阅它的消息
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类型。

上一篇下一篇

猜你喜欢

热点阅读