- 推荐: RxSwift官方文档
- 中文: RxSwift官方文档的中文翻译
并且,Observable sequence可以接受异步信号,也就是说,信号是可以异步给监听者的
其中SequenceType是Swift(2.3以前版本,之后的版本没有该协议)中的一个协议,比如Swift中的Array就遵循这个协议,通过这个协议,你可以这样的去操作一个Array
let array = [1,2,3,4,5]
let array2 = array.filter({$0 > 1}).map({$0 * 2})//4 6 8 10
var indexGenerator = array2.generate()
let fisrt = indexGenerator.next() // 4
let seoncd = indexGenerator.next() //6
enum Event {
case Next(Element) // 新的信号到来
case Error(ErrorType) // 信号发生错误,序列不会再产生信号
case Completed // 序列发送信号完成,不会再产生新的信号
}
protocol ObserverType {
func on(event: Event) //监听所有的信号
}
Observable分为两种
class Observable<Element> {
func subscribe(observer: Observer) -> Disposable //调用Disposable的方法来取消
}
当然,除了手动释放,RxSwift提供了一些操作符,比如 takeUntil来根据条件取消
sequence
.takeUntil(self.rx_deallocated) //当对象要释放的时候,取消监听
.subscribe {
print($0)
}
fileprivate lazy var bag = DisposeBag()
button1.addTarget(self, action: #selector(btn1Click(_:)), for: .touchUpInside)
button1.rx.tap.subscribe { (event) in
self.button1.setTitle("按钮1", for: .normal)
print("button1")
}.addDisposableTo(bag)
button2.rx.tap.subscribe { (event) in
self.textField2.text = "按钮2被点击了"
}.addDisposableTo(bag)
textField2.delegate = self
subscribe(<#T##on: (Event) -> Void##(Event) -> Void#>)
textField1.rx.text.subscribe { (event: Event) in
//将UITextField文字改变的内容显示在Label中
self.label1.text = event.element!
print(event.element!!)
}.addDisposableTo(bag)
textField2.rx.text.subscribe { (event: Event) in
print(event.element)//报警告
//输出: Optional(Optional("jun"))
}.addDisposableTo(bag)
subscribe(on: (Event) -> Void)
textField1.rx.text.subscribe(onNext: { (str: String?) in
self.label1.text = str!
}).addDisposableTo(bag)
label1.rx.observe(String.self, "text").subscribe(onNext: { (str: String?) in
print(str!)
}).addDisposableTo(bag)
label2.rx.observe(CGRect.self, "frame").subscribe(onNext: { (rect: CGRect?) in
print(rect!.width)
}).addDisposableTo(bag)
scrollView.contentSize = CGSize(width: 1000, height: 0)
scrollView.rx.contentOffset
.subscribe(onNext: { (point : CGPoint) in
print(point)
}).addDisposableTo(bag)
//创建bag
let bag = DisposeBag()
let neverSqu = Observable<String>.never()
neverSqu.subscribe { (_) in
//该语句不会执行
print("This will never be printed")
}.addDisposableTo(bag)
//调用Disposable的方法来取消
Observable.empty().subscribe { (event) in
//该语句只会执行一次
//输出: completed
print(event)
}.addDisposableTo(bag)
Observable.just(3).subscribe { (event) in
print(event)
/*该语句只会执行两次,分别输出
1) next(3),语句结果
2) completed, 结束事件
*/
}.addDisposableTo(bag)
Observable.just("jun").subscribe { (event) in
print(event)
/*该语句只会执行两次,分别输出
1) next(jun),语句结果
2) completed, 结束事件
*/
}.addDisposableTo(bag)
Observable.of("a", "b", "2", "5.3")
.subscribe(onNext: { print($0) })
.addDisposableTo(bag)
//会分别输出 "a", "b", "2", "5.3"
Observable.of("a", "b", "2", "5.3").subscribe(onNext: { (event) in
print(event)
/*该语句只会执行4次,分别输出
1) next(a),语句结果
2) next(b),语句结果
3) next(2),语句结果
4) next(3.5),语句结果
*/
}, onError: nil, onCompleted: nil, onDisposed: nil).addDisposableTo(bag)
//每一个闭包都设置设置了 一个默认值,故可以省略
Observable.from(["a", "b", "2", "5.3"]).subscribe { (event) in
print(event)
/*该语句只会执行5次,分别输出
1) next(a),语句结果
2) next(b),语句结果
3) next(2),语句结果
4) next(3.5),语句结果
5) completed, 结束事件
*/
}.addDisposableTo(bag)
fileprivate func myobserable() -> Observable {
return Observable.create({ (observal: AnyObserver) -> Disposable in
observal.onNext("abc")
observal.onNext("12")
observal.onCompleted()
return Disposables.create()
})
}
fileprivate func myJunst(element: String) -> Observable {
return Observable.create({ (observal: AnyObserver) -> Disposable in
observal.onNext(element)
observal.onCompleted()
return Disposables.create()
})
}
myobserable().subscribe(onNext: { print($0) }).addDisposableTo(bag)
//该语句只会执行2次,分别输出"abc", "12"
myJunst(element: "jun").subscribe(onNext: { print($0) }).addDisposableTo(bag)
//该语句只会执行2次,分别输出"jun"
Observable<Int>.range(start: 1, count: 4).subscribe { (event: Event<Int>) in
print(event)
/*该语句只会执行5次,分别输出
1) next(1),语句结果
2) next(2),语句结果
3) next(3),语句结果
4) next(4),语句结果
5) completed, 结束事件
*/
}.addDisposableTo(bag)
创建一个sequence,发出特定的事件n次
Observable.repeatElement("quanjun")
.take(3)
.subscribe(onNext: { print($0) })
.addDisposableTo(bag)
//该语句只会执行3次,每次都输出"quanjun"
let generate = Observable.generate(initialState: 0, condition: { $0 < 5 }, iterate: { $0 + 2 })
generate.subscribe({ print($0) }).addDisposableTo(bag)
/*1> 输出顺序:
next(0)
next(2)
next(4)
completed
2> 以上代码可以理解为for循环处理逻辑
for (Int i = 0; i < 5; i++) {
print(i)
}
*/
let error = NSError(domain: "错误", code: 10, userInfo: nil) as Error
Observable.error(error)
.subscribe({ print($0) })
.addDisposableTo(bag)
//输出: error(Error Domain=错误 Code=10 "(null)")
let pSubject = PublishSubject()
pSubject.subscribe { (event: Event) in
print("2--", event)
}.addDisposableTo(bag)
print("1--------------")
pSubject.onNext("T")
pSubject.onNext("Q")
pSubject.subscribe { (event: Event) in
print("3--", event)
}.addDisposableTo(bag)
pSubject.onNext("J")
/*输出顺序为:
1--------------
2-- next(T)
2-- next(Q)
2-- next(J)
3-- next(J)
*/
createUnbounded()
表示接受所有事件create(bufferSize: 4)
表示可接受到的订阅他之前的事件的个数,但是订阅他之后的事件一定会触发createUnbounded()
表示接受所有事件let rSubject = ReplaySubject.createUnbounded()
rSubject.onNext("T")
rSubject.onNext("Q")
rSubject.subscribe { (event: Event) in
print("0--", event)
}.addDisposableTo(bag)
rSubject.onNext("J")
/*输出顺序为:
0-- next(T)
0-- next(Q)
0-- next(J)
*/
create(bufferSize: 4)
表示可接受到的订阅他之前的事件的个数let rSubject1 = ReplaySubject.create(bufferSize: 1)
rSubject1.onNext("T")
rSubject1.onNext("Q")
rSubject1.subscribe { (event: Event) in
print("4--", event)
}.addDisposableTo(bag)
rSubject1.onNext("J")
/*输出顺序为:
4-- next(Q)
4-- next(J)
*/
let bSubject = BehaviorSubject(value: "G")
bSubject.subscribe { (event: Event<String>) in
print("5--", event)
}.addDisposableTo(bag)
bSubject.onNext("Y")
bSubject.onNext("Q")
bSubject.subscribe { (event: Event<String>) in
print("6--", event)
}.addDisposableTo(bag)
bSubject.onNext("J")
/*输出顺序为:
5-- next(G)
5-- next(Y)
5-- next(Q)
6-- next(Q)
5-- next(J)
6-- next(J)
*/
let variable = Variable("S")
variable.asObservable().subscribe { (event) in
print("7--", event)
}.addDisposableTo(bag)
variable.value = "D"
variable.value = "Q"
variable.asObservable().subscribe { (event) in
print("8--", event)
}.addDisposableTo(bag)
variable.value = "j"
/*输出顺序为:
7-- next(S)
7-- next(D)
7-- next(Q)
8-- next(Q)
7-- next(j)
8-- next(j)
7-- completed
8-- completed
*/
Observable.of(1, 2, 3, 4)
.map({ $0 * $0 })
.subscribe(onNext: { print($0) })
.addDisposableTo(bag)
/* 输出顺序为:
1
4
9
16
*/
首先创建一个struct
struct Student {
var score: Variable
}
flatMap执行代码
let stu1 = Student(score: Variable(80))
let stu2 = Student(score: Variable(100))
let student = Variable(stu1)
student.asObservable().flatMap { (stu: Student) -> Observable in
return stu.score.asObservable()
}.subscribe { (event) in
print(event)
}.addDisposableTo(bag)
student.value = stu2
stu1.score.value = 10
stu2.score.value = 20
/* 输出顺序为:
next(80.0)
next(100.0)
next(10.0)
next(20.0)
completed
*/
let stu3 = Student(score: Variable(70))
let stu4 = Student(score: Variable(60))
let student1 = Variable(stu3)
student1.asObservable().flatMapFirst { (stu) -> Observable in
return stu.score.asObservable()
}.subscribe { (event: Event) in
print(event)
}.addDisposableTo(bag)
student1.value = stu4
stu3.score.value = 10
stu4.score.value = 20
/* 输出顺序为:
next(70.0)
next(10.0)
completed
*/
let testVariable = Variable("jun")
testVariable.asObservable().subscribe { (event : Event) in
print(event)
}.dispose()
testVariable.value = "tian"
/* 输出顺序为:
next(jun)
completed
*/
fileprivate lazy var bag = DisposeBag()
在代码结尾调用
.addDisposableTo(bag)
方法
extension Reactive where Base: UITextField {
var inputEnabled: UIBindingObserver {
return UIBindingObserver(UIElement: base) { textFiled, result in
textFiled.isEnabled = result.isValid
}
}
}
后续会继续更新,敬请关注