在RxsWift中还有一种非常特殊的序列 Subject- 即序列也为观察者
Subject是一个代理,它既是Observer,也是Observable
一、PublishSubject
- 只会订阅到订阅之后发送的信号,订阅不到订阅之前发送的信号
// 1:初始化序列
let publishSub = PublishSubject<Int>() //初始化一个PublishSubject 装着Int类型的序列
// 2:发送响应序列
publishSub.onNext(1)
// 3:订阅序列
publishSub.subscribe { (a) in
print("订阅到了:",a)
}.disposed(by: disposeBag)
// 再次发送响应
publishSub.onNext(2)
publishSub.onNext(3)
订阅到了: next(2)
订阅到了: next(3)
二、BehaviorSubject
- 有一个初始信号,订阅之前保留一个初始信号
// 1:创建序列
let behaviorSubject = BehaviorSubject.init(value: 100)
// 2:发送信号
behaviorSubject.onNext(2)
behaviorSubject.onNext(3)
// 3:订阅序列
behaviorSubject.subscribe { (a) in
print("订阅到了:",a)
}.disposed(by: disposeBag)
// 再次发送
behaviorSubject.onNext(4)
behaviorSubject.onNext(5)
// 再次订阅
behaviorSubject.subscribe { (b) in
print("订阅到了:",b)
}.disposed(by: disposeBag)
订阅到了: next(3)
订阅到了: next(4)
订阅到了: next(5)
订阅到了: next(5)
三、ReplaySubject
- 可以设置订阅之前,发送信号的个数
// 1:创建序列
let replaySub = ReplaySubject<Int>.create(bufferSize: 2)
// let replaySub = ReplaySubject<Int>.createUnbounded()
// 2:发送信号
replaySub.onNext(1)
replaySub.onNext(2)
replaySub.onNext(3)
replaySub.onNext(4)
// 3:订阅信号
replaySub.subscribe { (a) in
print("订阅到了:",a,"订阅到了:",a)
}.disposed(by: disposeBag)
replaySub.onNext(7)
replaySub.onNext(8)
replaySub.onNext(9)
订阅到了: next(3) 订阅到了: next(3)
订阅到了: next(4) 订阅到了: next(4)
订阅到了: next(7) 订阅到了: next(7)
订阅到了: next(8) 订阅到了: next(8)
订阅到了: next(9) 订阅到了: next(9)
四、AsyncSubject
4.1 如果有onCompleted(),会执行onCompleted()之前最近发送的一条信号和onCompleted信号,结束
订阅到了 next(4)
订阅到了 completed
4.2 如果有onError,只会执行onError,结束
4.3 如果既有onCompleted也有onError,谁在前执行谁,然后结束,不再执行
4.4 都没有,不执行
// 1:创建序列
let asynSub = AsyncSubject<Int>.init()
// 2:发送信号
asynSub.onNext(1)
asynSub.onNext(2)
// 3:订阅序列
asynSub.subscribe { (a) in
print("订阅到了:",a)
}.disposed(by: disposeBag)
// 再次发送
asynSub.onNext(3)
asynSub.onNext(4)
asynSub.onError(NSError.init(domain: "dyz", code: 100, userInfo: nil))
asynSub.onCompleted()
订阅到了: error(Error Domain=dyz Code=100 "(null)")
五、Variable
- 有一个初始信号,订阅之前保留一个初始信号
// Variable : 5.0已经废弃(BehaviorRelay 替换) - 这里板书 大家可以了解一下
// 1:创建序列
let variableSub = Variable.init(1)
// 2:发送信号
variableSub.value = 100
variableSub.value = 10
// 3:订阅信号
variableSub.asObservable().subscribe { (a) in
print("订阅到了:",a)
}.disposed(by: disposeBag)
// 再次发送
variableSub.value = 1000
订阅到了: next(10)
订阅到了: next(1000)
六、BehaviorRelay
- 有一个初始信号,订阅之前保留一个初始信号
- 从打印看,执行了completed
- behaviorRelay.accept 相当于发送信号
- behaviorRelay.value 获取响应的值,只有get方法,没有set方法,只读
let behaviorRelay = BehaviorRelay(value: 100)
behaviorRelay.subscribe { (a) in
print(a)
}.disposed(by: disposbag)
print("打印:\(behaviorRelay.value)")
behaviorRelay.accept(1000)
next(100)
打印:100
next(1000)
completed
网友评论