推薦書本:RxSwift
電子版地址:https://pan.baidu.com/s/1bp8MlC7 密碼 5tjx
本文是RxSwift書本 學(xué)習(xí)筆記
書本code地址:https://pan.baidu.com/s/1o7GVBrO
Subject 可以看做是一種代理和橋梁次询。它既是訂閱者又是訂閱源。
作為一個(gè)觀察者和觀察者店印。您早就看到了他們?nèi)绾谓邮帐录⒂嗛啞T撝黝}接收到下一個(gè)事件咐蝇,每次收到一個(gè)事件時(shí)已脓,它都會(huì)將它發(fā)送給它的訂閱者。
當(dāng)你訂閱PublishSubject的時(shí)候怪得,你只能接收到訂閱他之后發(fā)生的事件甜害。subject.onNext()發(fā)出onNext事件舶掖,對(duì)應(yīng)的還有onError()和onCompleted()事件
func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) {
sequence
.subscribe { e in
print("Subscription: \(name), event: \(e)")
}
}
example(of: "PublishSubject") {
let subject = PublishSubject<String>()
writeSequenceToConsole(name: "1", sequence: subject)
subject.onNext("Is anyone Listeing?")
subject.on(.next("1"))
subject.on(.next("2"))
writeSequenceToConsole(name: "2", sequence: subject)
subject.onNext("Is anyone Listeing?")
subject.on(.next("1"))
subject.on(.next("2"))
}
ReplaySubject 在新的訂閱對(duì)象訂閱的時(shí)候會(huì)補(bǔ)發(fā)所有已經(jīng)發(fā)送過(guò)的數(shù)據(jù)隊(duì)列眨攘, bufferSize 是緩沖區(qū)的大小,決定了補(bǔ)發(fā)隊(duì)列的最大值嚣州。如果 bufferSize 是1鲫售,那么新的訂閱者出現(xiàn)的時(shí)候就會(huì)補(bǔ)發(fā)上一個(gè)事件,如果是2该肴,則補(bǔ)兩個(gè)情竹,以此類推。(距觀察匀哄,補(bǔ)發(fā)的事件是先進(jìn)后出)
![Uploading image_072992.png . . .]
example(of: "ReplaySubject") {
let subject = ReplaySubject<String>.create(bufferSize: 1)
writeSequenceToConsole(name: "1", sequence: subject)
subject.onNext("Is anyone Listeing? 1")
subject.on(.next("a"))
subject.on(.next("b"))
writeSequenceToConsole(name: "2", sequence: subject)
subject.onNext("Is anyone Listeing? 2")
subject.on(.next("c"))
subject.on(.next("d"))
}
========================================
BehaviorSubject
BehaviorSubject 在新的訂閱對(duì)象訂閱的時(shí)候會(huì)發(fā)送最近發(fā)送的事件,如果沒有則發(fā)送一個(gè)默認(rèn)值拱雏。
================================
Variable
Variable 是基于 BehaviorSubject 的一層封裝底扳,它的優(yōu)勢(shì)是:不會(huì)被顯式終結(jié)铸抑。即:不會(huì)收到 .Completed 和 .Error 這類的終結(jié)事件,它會(huì)主動(dòng)在析構(gòu)的時(shí)候發(fā)送 .Complete 衷模。
================================
Variable
Variable 是基于 BehaviorSubject 的一層封裝鹊汛,它的優(yōu)勢(shì)是:不會(huì)被顯式終結(jié)蒲赂。即:不會(huì)收到 .Completed 和 .Error 這類的終結(jié)事件,它會(huì)主動(dòng)在析構(gòu)的時(shí)候發(fā)送 .Complete 刁憋。
需要通過(guò)asObservable()方法來(lái)訪問(wèn)其behavior subject.主題
example(of: "Variable") {
let variable = Variable("z")
let disposeBag = DisposeBag()
variable.value = "new initial"
variable.asObservable().subscribe{print("1)\($0)")}.addDisposableTo(disposeBag)
}