响应机制核心是 Observable 和 ObserverType. 前者用来发送事件,使用者可以订阅(subscribe)后,监听 onNext ,onError等事件。 样例代码:
let switch = UISwitch! = UISwitch.init(frame: CGRect(x: 0, y: 50, width: 100, height: 40))
Let swiOnEvent = switch.rx.isOn
swiOnEvent.subscribe(onNext: { booValue in
print(“isOn=\(booValue)")
}, onError: { i in
})
Observable 的 map 可以在监听到onNext 事件后,将当前Observable的 element 换成自定义的其他类型,并返回一个对应泛型的Observable。 样例代码:
let switch = UISwitch! = UISwitch.init(frame: CGRect(x: 0, y: 50, width: 100, height: 40))
Let swiOnEvent = switch.rx.isOn
swiOnEvent.map{ isOn in //isOn 是swiOnEvent的泛型类型,也就是 Bool
return 12 //换成Int了
}.subscribe(onNext: { intValue in //作为int来用了
print("st=\(intValue)")
}
Observable 的filter 可以通过自定义条件来过滤发送 onNext事件,并返回一个同样泛型的Observable。
样例代码:
let switch = UISwitch! = UISwitch.init(frame: CGRect(x: 0, y: 50, width: 100, height: 40))
Let swiOnEvent = switch.rx.isOn
swiOnEvent.filter{ isOn in
//这里转变一下条件,只有 isOn’ 是false时,该observable 才发送onNext事件
If isOn {
Return false
}
Return true
}.subscribe(onNext: { boolValue in
//由于filter里,只有 isOn 为false时,才发送next事件,因此这里的boolValue 一定是false
print("st=\(boolValue)")
}
Filter 和 map 能嵌套组合使用,最后构造出自己需要的 Observable 用 filter来过滤监听到的值。 再接map 来转换Observable的泛型数据类型。
//声明和创建 Observable
typealias CustomFrame = (CGPoint, CGSize)
private var myPointObsevablePtr : (AnyObserver<CustomFrame>)?
public lazy var myPointObsevable : Observable<CustomFrame> = {
Observable<CustomFrame>.create { [weak self] (ob) -> Disposable in
self?.myPointObsevablePtr = ob
return Disposables.create()
}
}()
//在需要的时机,抛出onNext事件
self?.myPointObsevablePtr?.onNext((position, CGSize(width: 500, height: 1000)))
然后 myPointObsevable 给外面订阅监听即可。