RxSwift<10>—— Subject即攻也守

2019-10-21  本文已影响0人  Gollum_

Subject既可以做序列,也可以做观察者
攻守兼备

首先我们来看看:SubjectType的原理!

public protocol SubjectType : ObservableType {
      // 关联了观察者类型,具备这个类型的能力
    associatedtype SubjectObserverType : ObserverType
    func asObserver() -> SubjectObserverType
}
// 1:初始化序列
let publishSub = PublishSubject<Int>() 
// 2:发送响应序列
publishSub.onNext(1)
// 3:订阅序列
publishSub.subscribe { print("订阅到了:",$0)}
    .disposed(by: disposbag)
// 再次发送响应
publishSub.onNext(2)
publishSub.onNext(3)

各种Subject
PublishSubject
可以不需要初始来进行初始化(也就是可以为空),并且它只会向订阅者发送在订阅之后才接收到的元素

//1:初始化序列
        let publishSub = PublishSubject<Int>()
        // 2:发送响应序列
        publishSub.onNext(1)
        // 3:订阅序列
        publishSub.subscribe{print($0)}
        .disposed(by: disposeBag)
        publishSub.onNext(2)
        publishSub.onNext(3)

BehaviorSubject
通过一个默认初始值来创建,当订阅者订阅BehaviorSubject时,会收到订阅后Subject上一个发出的Event,如果还没有收到任何数据,会发出一个默认值。之后就和PublishSubject一样,正常接收新的事件。

let behaviorSub = BehaviorSubject.init(value: 100)
        
        behaviorSub.onNext(101)
        behaviorSub.onNext(102)
        behaviorSub.subscribe{print($0)}.disposed(by: disposeBag)
        behaviorSub.onNext(103)
        behaviorSub.onNext(104)
        behaviorSub.subscribe{print($0)}.disposed(by: disposeBag)

ReplaySubject
ReplaySubject 发送源Observable 的所有事件无论observer什么时候开始订阅。

// 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{ print("订阅到了:",$0)}
    .disposed(by: disposbag)
// 再次发送
replaySub.onNext(7)
replaySub.onNext(8)
replaySub.onNext(9)
let behaviorRelay = BehaviorRelay(value: 100)
behaviorRelay.subscribe(onNext: { (num) in
    print(num)
.disposed(by: disposbag)
print("打印:\(behaviorRelay.value)")

behaviorRelay.accept(1000)
上一篇下一篇

猜你喜欢

热点阅读