-
首先,何为
RxSwift
?
RxSwift
是ReactiveX
的Swift
版本,一个响应式变成框架。传送门
-
开始之前,先介绍两个
function
,并没有什么实质性作用,只是为了方便学习演示
/**
延迟`delay`时长之后执行`closure`闭包
- parameter delay: 闭包延迟执行时间
- parameter closure: 返回值`Void`的闭包
*/
public func delay(_ delay: Double, closure: @escaping (Swift.Void) -> Swift.Void)
/**
起到一个分割线作用
- parameter description: example 简介
- parameter action: 返回值`Void`的闭包
*/
public func example(_ description: String, action: (Swift.Void) -> Swift.Void)
-
RxSwift
基础
Observable
:Observable
是观察着模式中的被观察对象,相当于一个事件序列GeneratorType
,它会向它的订阅者发送事件信息,
-
next()
:一个新的事件 -
complete()
:完成事件 -
error()
: 错误事件
多数情况都是对不同的
Observable
进行subscribe
操作,并在接收到事件后进行相应的操作
-
名词解释
-
DisposeBag
相当于一个
autoreleasepool(自动释放池)
,对观察者进行管理,在适当的时候销毁观察者
-
Observable
Observables will not execute their subscription closure unless there is a subscriber
Observables只有被订阅之后才会被执行,否则不予执行
```
example("一个未被订阅的Observable") {
_ = Observable<String>.create { observerOfString -> Disposable in
print("This will never be printed")
observerOfString.on(.next("😬"))
observerOfString.on(.completed)
return Disposables.create()
}
}
//不会打印任何数据,因为该Observable没有被订阅
- ###### subscribe
> subscribe是订阅`sequence`发出的事件,比如`next`事件,`error`事件等。而`subscribe(onNext:)`是监听`sequence`发出的`next`事件中的`element`进行处理,他会忽略`error`和`completed`事件。相对应的还有`subscribe(onError:) `和 `subscribe(onCompleted:)`
```
example("被订阅的Observable") {
let disposeBag = DisposeBag()
Observable<String>.create { observerOfString in
print("Observable created")
observerOfString.on(.next("😉"))
observerOfString.on(.completed)
return Disposables.create()
}
.subscribe { event in
print(event)
}.addDisposableTo(disposeBag)
}
执行结果:
--- 被订阅的Observable ---
Observable created
next(😉)
completed
-
Creating and Subscribing to Observables
/ 创建并订阅Observables
-
never
创建一个空序列,不发送任何事件
example("never") {
let disposeBag = DisposeBag()
let neverSequence = Observable<String>.never()
neverSequence
.subscribe { _ in
print("This will never be printed")
}
.addDisposableTo(disposeBag)
}
-
empty
一个空的序列,它只发送 .Completed 消息
example("empty") {
let disposeBag = DisposeBag()
Observable<Int>.empty()
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
}
//执行结果:
--- empty example ---
completed
-
just
只包含一个元素的序列,发送一个next事件和completed事件
example("just") {
let disposeBag = DisposeBag()
Observable.just("🔴")
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
}
//执行结果:
--- just example ---
next(🔴)
completed
-
of
将所有元素依次转换为序列发送
example("of") {
let disposeBag = DisposeBag()
Observable.of("🐶", "🐱", "🐭", "🐹")
.subscribe(onNext: { element in
print(element)
})
.disposed(by: disposeBag)
}
//执行结果
--- of example ---
🐶
🐱
🐭
🐹
-
from
从数组或字典或集合的所有元素创建序列发送
example("from") {
let disposeBag = DisposeBag()
Observable.from(["🐶", "🐱", "🐭", "🐹"])
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
//执行结果
--- from example ---
🐶
🐱
🐭
🐹
-
create
创建一个自定义Observable
example("create") {
let disposeBag = DisposeBag()
let myJust = { (element: String) -> Observable<String> in
return Observable.create { observer in
observer.on(.next(element))
observer.on(.completed)
return Disposables.create()
}
}
myJust("🔴")
.subscribe { print($0) }
.disposed(by: disposeBag)
}
//执行结果:
--- create example ---
next(🔴)
completed
-
error
创建一个只发送error事件的Observable
example("error") {
let disposeBag = DisposeBag()
Observable<Int>.error(TestError.test)
.subscribe { print($0) }
.disposed(by: disposeBag)
}
//执行结果:
--- error example ---
error(test)
-
Subject
Subject
可以订阅别的Observable
,也可以被订阅并给它的订阅者发送事件
常用:
PublishSubject
ReplaySubject
BehaviorSubject
Variable
-
PublishSubject
它的订阅者只能接收到订阅后发送的事件,无法接收到订阅之前的事件
example("PublishSubject") {
let disposeBag = DisposeBag()
let subject = PublishSubject<String>()
subject.addObserver("1").disposed(by: disposeBag)
subject.onNext("🐶")
subject.onNext("🐱")
subject.addObserver("2").disposed(by: disposeBag)
subject.onNext("🅰️")
subject.onNext("🅱️")
}
//执行结果:
--- PublishSubject example ---
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
-
ReplaySubject
它的订阅者定接收到订阅之后发出的事件,并且能接收到订阅之前的信号,至于能接收到订阅之前的多少个信号则由 bufferSize 参数决定
example("ReplaySubject") {
let disposeBag = DisposeBag()
let subject = ReplaySubject<String>.create(bufferSize: 1)
subject.addObserver("1").disposed(by: disposeBag)
subject.onNext("🐶")
subject.onNext("🐱")
subject.addObserver("2").disposed(by: disposeBag)
subject.onNext("🅰️")
subject.onNext("🅱️")
}
//执行结果:
--- ReplaySubject example ---
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
-
BehaviorSubject
它的订阅者定接收到订阅之后发出的事件,并且能接收到订阅之前的前一个信号
example("BehaviorSubject") {
let disposeBag = DisposeBag()
let subject = BehaviorSubject(value: "🔴")
subject.addObserver("1").disposed(by: disposeBag)
subject.onNext("🐶")
subject.onNext("🐱")
subject.addObserver("2").disposed(by: disposeBag)
subject.onNext("🅰️")
subject.onNext("🅱️")
subject.addObserver("3").disposed(by: disposeBag)
subject.onNext("🍐")
subject.onNext("🍊")
}
//执行结果:
--- BehaviorSubject example ---
Subscription: 1 Event: next(🔴)
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
Subscription: 3 Event: next(🅱️)
Subscription: 1 Event: next(🍐)
Subscription: 2 Event: next(🍐)
Subscription: 3 Event: next(🍐)
Subscription: 1 Event: next(🍊)
Subscription: 2 Event: next(🍊)
Subscription: 3 Event: next(🍊)
-
Variable
它的订阅者定接收到订阅之后发出的事件和订阅之前的前一个信号,并且当它的 value 发生改变时所有的订阅者能收到事件,完成后向所有订阅者发送 complete 事件
example("Variable") {
let disposeBag = DisposeBag()
let variable = Variable("🔴")
variable.asObservable().addObserver("1").disposed(by: disposeBag)
variable.value = "🐶"
variable.value = "🐱"
variable.asObservable().addObserver("2").disposed(by: disposeBag)
variable.value = "🅰️"
variable.value = "🅱️"
}
//执行结果:
--- Variable example ---
Subscription: 1 Event: next(🔴)
Subscription: 1 Event: next(🐶)
Subscription: 1 Event: next(🐱)
Subscription: 2 Event: next(🐱)
Subscription: 1 Event: next(🅰️)
Subscription: 2 Event: next(🅰️)
Subscription: 1 Event: next(🅱️)
Subscription: 2 Event: next(🅱️)
Subscription: 1 Event: completed
Subscription: 2 Event: completed
-
组合操作
-
startWith
这个不好描述,看代码,别说话,用心去感受
example("startWith") {
let disposeBag = DisposeBag()
Observable.of("🐶", "🐱", "🐭", "🐹")
.startWith("1")
.startWith("2")
.startWith("3", "🅰️", "🅱️")
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
//执行结果:
--- startWith example ---
3
🅰️
🅱️
2
1
🐶
🐱
🐭
🐹
-
merge
把两个队列按照顺序组合在一起
example("merge") {
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1, subject2)
.merge()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("🅰️")
subject1.onNext("🅱️")
subject2.onNext("①")
subject2.onNext("②")
subject1.onNext("🆎")
subject2.onNext("③")
}
//执行结果:
--- merge example ---
🅰️
🅱️
①
②
🆎
③
-
zip
将多个序列组合在一起,当所有序列能凑成一组(一一对应)时才发送事件
example("zip") {
let disposeBag = DisposeBag()
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
stringSubject.onNext("🅰️")
stringSubject.onNext("🅱️")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("🆎")
intSubject.onNext(3)
}
//执行结果:
--- zip example ---
🅰️ 1
🅱️ 2
🆎 3
-
combineLatest
多个序列合并,每个序列的最新值进行组合
example("combineLatest") {
let disposeBag = DisposeBag()
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.combineLatest(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
stringSubject.onNext("🅰️")
stringSubject.onNext("🅱️")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("🆎")
}
//执行结果:
--- combineLatest example ---
🅱️ 1
🅱️ 2
🆎 2
-
转换操作
-
map
对序列的值做转换操作后返回,序列的值发生改变
example("map") {
let disposeBag = DisposeBag()
Observable.of(1, 2, 3)
.map { $0 * $0 } //1*1 2*2 3*3
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
//执行结果:
--- map example ---
1
4
9
-
flatMap and flatMapLatest
看代码
example("flatMap and flatMapLatest") {
let disposeBag = DisposeBag()
struct Player {
var score: Variable<Int>
}
let 👦🏻 = Player(score: Variable(80))
let 👧🏼 = Player(score: Variable(90))
let player = Variable(👦🏻)
player.asObservable()
.flatMap { $0.score.asObservable() } // Change flatMap to flatMapLatest and observe change in printed output
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
👦🏻.score.value = 85
player.value = 👧🏼
👦🏻.score.value = 95 // Will be printed when using flatMap, but will not be printed when using flatMapLatest
👧🏼.score.value = 100
}
//执行结果:
--- flatMap and flatMapLatest example ---
80
85
90
95
100