Demo 项目地址
Observable.never()
.subscribe{
print($0)
}.disposed(by: GlobalDisposeBag)
无任何输出
Observable.empty()
.subscribe{
print($0)
}.disposed(by: GlobalDisposeBag)
输出:
completed
Observable.error(ExampleError)
.subscribe{
print($0)
}.disposed(by: GlobalDisposeBag)
输出:
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
Observable.just("onlyMe")
.subscribe{
print($0)
}.disposed(by: GlobalDisposeBag)
输出:
next(onlyMe)
completed
Observable.of("a","b","c")
.subscribe{
print($0)
}.disposed(by: GlobalDisposeBag)
输出:
next(a)
next(b)
next(c)
completed
Observable.from(["1", "2", "3", "4"])
.subscribe(onNext: { print($0) })
.disposed(by: GlobalDisposeBag)
输出:
next(a)
next(b)
next(c)
completed
let arr = [1,2,3,4]
Observable.create { observer in
var index = 0
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if index >= arr.count{
observer.onCompleted()
timer.invalidate()
}else{
observer.onNext(arr[index])
}
index = index + 1
})
return Disposables.create()
}
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
next(4)
completed
注:这里的 Observable 必须是 Observable, 因为该操作符是用于整型数的
Observable.range(start: 1, count: 5)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
next(4)
next(5)
completed
Observable.generate(
initialState: 0,
condition: { $0 < 3 },
iterate: { $0 + 1 }
)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(0)
next(1)
next(2)
completed
defer
var seqFlag = 0
let deferredSequence = Observable.deferred {
seqFlag += 1
print("创建序列 seqFlag:\(seqFlag)")
return Observable.create { observer in
observer.onNext(String(seqFlag) + "a")
observer.onNext(String(seqFlag) + "b")
observer.onCompleted()
return Disposables.create()
}
}
print("订阅1")
deferredSequence
.subscribe {print($0)}
.disposed(by: GlobalDisposeBag)
print("订阅2")
deferredSequence
.subscribe {print($0)}
.disposed(by: GlobalDisposeBag)
输出:
订阅1
创建序列 seqFlag:1
next(1a)
next(1b)
completed
订阅2
创建序列 seqFlag:2
next(2a)
next(2b)
completed
Observable.interval(1, scheduler: MainScheduler.asyncInstance)
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
输出:
next(0)
next(1)
next(2)
next(3)
next(4)
next(5)
.............
let seq = Observable<Int>.timer(2, period: 1,scheduler: MainScheduler.asyncInstance)
print("订阅 time:",Date())
seq.subscribe{print("收到事件:",$0,"time:",Date())}
.disposed(by: GlobalDisposeBag)
输出:
订阅 time: 2018-03-23 03:06:49 +0000
收到事件: next(0) time: 2018-03-23 03:06:51 +0000
收到事件: next(1) time: 2018-03-23 03:06:52 +0000
收到事件: next(2) time: 2018-03-23 03:06:53 +0000
收到事件: next(3) time: 2018-03-23 03:06:54 +0000
收到事件: next(4) time: 2018-03-23 03:06:55 +0000
收到事件: next(5) time: 2018-03-23 03:06:56 +0000
收到事件: next(6) time: 2018-03-23 03:06:57 +0000
............
let ob = Observable.of("a", "b", "c", "d")
.startWith("1")
.startWith("2")
.startWith("3", "4", "5")
ob.subscribe(onNext: { print($0) })
.disposed(by: GlobalDisposeBag)
输出:
3
4
5
2
1
a
b
c
d
let disposeBag = DisposeBag()
let subject1 = PublishSubject()
let subject2 = PublishSubject()
Observable.merge([subject1,subject2])
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("?️")
subject1.onNext("?️")
subject2.onNext("①")
subject2.onNext("②")
subject1.onNext("?")
subject2.onNext("③")
输出:
?️
?️
①
②
?
③
let subject1 = PublishSubject()
let subject2 = PublishSubject()
Observable.of(subject1, subject2)
.merge()
.subscribe {print($0)}
.disposed(by: GlobalDisposeBag)
subject1.onNext("?️")
subject1.onNext("?️")
subject2.onNext("①")
subject2.onNext("②")
subject1.onError(ExampleError)
subject2.onNext("③")
输出:
next(?️)
next(?️)
next(①)
next(②)
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let subject1 = PublishSubject()
let subject2 = PublishSubject()
Observable.of(subject1, subject2)
.merge()
.subscribe {print($0)}
.disposed(by: GlobalDisposeBag)
subject1.onNext("?️")
subject1.onNext("?️")
subject2.onNext("①")
subject2.onNext("②")
subject1.onCompleted()
subject2.onNext("③")
subject2.onCompleted()
输出:
next(?️)
next(?️)
next(①)
next(②)
next(③)
completed
zip弹珠图
let stringSubject = PublishSubject()
let intSubject = PublishSubject()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
stringSubject.onNext("?️")
stringSubject.onNext("?️")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("?")
intSubject.onNext(3)
输出:
next(?️ 1)
next(?️ 2)
next(? 3)
let stringSubject = PublishSubject()
let intSubject = PublishSubject()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
stringSubject.onNext("a")
stringSubject.onNext("b")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("c")
stringSubject.onNext("d")
stringSubject.onError(ExampleError)
intSubject.onNext(3)
intSubject.onCompleted()
输出:
next(a 1)
next(b 2)
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let stringSubject = PublishSubject()
let intSubject = PublishSubject()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
stringSubject.onNext("a")
stringSubject.onNext("b")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("c")
stringSubject.onNext("d")
stringSubject.onCompleted()
intSubject.onNext(3)
intSubject.onCompleted()
输出:
next(a 1)
next(b 2)
next(c 3)
completed
let stringSubject = PublishSubject()
let intSubject = PublishSubject()
Observable.combineLatest(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: GlobalDisposeBag)
stringSubject.onNext("?️")
stringSubject.onNext("?️")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("?")
输出:
?️ 1
?️ 2
? 2
let subSeq1 = PublishSubject.init()
let subSeq2 = PublishSubject.init()
let sourceSeq = PublishSubject>.init()
sourceSeq.switchLatest()
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
sourceSeq.onNext(subSeq1)
subSeq1.onNext("1a")
subSeq1.onNext("1b")
sourceSeq.onNext(subSeq2)
subSeq1.onNext("1c") //这个1c不会输出 因为订阅会切换到最新的序列上 (subSeq2)
subSeq2.onNext("2a")
subSeq2.onNext("2b")
sourceSeq.onNext(subSeq1)
subSeq1.onNext("1d") //此时会输出 1d 因为subSeq1被发射,订阅切换到 subSeq1 上
输出:
next(1a)
next(1b)
next(2a)
next(2b)
next(1d)
let subSeq1 = PublishSubject.init()
let subSeq2 = PublishSubject.init()
let sourceSeq = PublishSubject>.init()
sourceSeq.switchLatest()
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
sourceSeq.onNext(subSeq1)
subSeq1.onNext("1a")
subSeq1.onNext("1b")
sourceSeq.onNext(subSeq2)
subSeq2.onNext("2a")
subSeq2.onNext("2b")
sourceSeq.onCompleted()
subSeq2.onNext("2c") //会输出
输出:
next(1a)
next(1b)
next(2a)
next(2b)
next(2c)
let subSeq1 = PublishSubject.init()
let subSeq2 = PublishSubject.init()
let sourceSeq = PublishSubject>.init()
sourceSeq.switchLatest()
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
sourceSeq.onNext(subSeq1)
subSeq1.onNext("1a")
subSeq1.onNext("1b")
sourceSeq.onNext(subSeq2)
subSeq2.onNext("2a")
subSeq2.onNext("2b")
sourceSeq.onCompleted()
subSeq2.onCompleted()
subSeq2.onNext("2c") //不会输出
输出:
next(1a)
next(1b)
next(2a)
next(2b)
completed
let subSeq1 = PublishSubject.init()
let subSeq2 = PublishSubject.init()
let sourceSeq = PublishSubject>.init()
sourceSeq.switchLatest()
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
sourceSeq.onNext(subSeq1)
subSeq1.onNext("1a")
subSeq1.onNext("1b")
sourceSeq.onNext(subSeq2)
subSeq2.onNext("2a")
subSeq2.onNext("2b")
//subSeq2.onError(ExampleError)//订阅序列异常终止的场景,与 sourceSeq异常终止的效果一样。去除注释运行可以查看效果。
sourceSeq.onError(ExampleError)
输出:
next(1a)
next(1b)
next(2a)
next(2b)
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
//过滤奇数
Observable.of(1,2,3,4,5)
.filter {
$0 % 2 == 0
}
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(2)
next(4)
completed
Observable.of(1,2)
.ignoreElements()
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
输出:
completed
//过滤连续相同元素
Observable.of(1,2,3,3,4,5,5,6,5,6,7)
.distinctUntilChanged()
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)
next(5)
next(6)
next(7)
completed
Observable.of("a","b","c","d")
.elementAt(2)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(c)
completed
Observable.of(1,2,3,5)
.take(2)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
completed
let seq = Observable.create { (observer) -> Disposable in
var i = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if i <= 4{
observer.onNext(i)
i = i+1
}else{
observer.onCompleted()
timer.invalidate()
//如果是 异常终止 ,则不会发射数据
//observer.onError("Some error")
}
}).fire()
return Disposables.create()
}.takeLast(3)
print("订阅 time: ", Date())
seq.subscribe{print("收到事件:",$0," time: ",Date())}
.disposed(by: GlobalDisposeBag)
输出:
订阅 time: 2018-03-23 04:16:41 +0000
收到事件: next(2) time: 2018-03-23 04:16:45 +0000
收到事件: next(3) time: 2018-03-23 04:16:45 +0000
收到事件: next(4) time: 2018-03-23 04:16:45 +0000
收到事件: completed time: 2018-03-23 04:16:45 +0000
Observable.of(1, 2, 3, 4, 5, 6)
.takeWhile { $0 < 4 }
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
completed
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext("1")
sourceSequence.onNext("2")
sourceSequence.onNext("3")
print("参照序列发射元素")
referenceSequence.onNext("a")
sourceSequence.onNext("4")
sourceSequence.onNext("5")
sourceSequence.onNext("6")
输出:
next(1)
next(2)
next(3)
参照序列发射元素
completed
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext("1")
sourceSequence.onNext("2")
sourceSequence.onNext("3")
print("参照序列异常终止")
referenceSequence.onError("Some Error")
sourceSequence.onNext("4")
sourceSequence.onNext("5")
sourceSequence.onNext("6")
输出:
next(1)
next(2)
next(3)
参照序列异常终止
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext("1")
sourceSequence.onNext("2")
sourceSequence.onNext("3")
referenceSequence.onNext("a")
print("参照序列正常终止")
referenceSequence.onCompleted()
sourceSequence.onNext("4")
sourceSequence.onNext("5")
sourceSequence.onNext("6")
输出:
next(1)
next(2)
next(3)
completed
参照序列正常终止
Observable.of(1,2,3,4,5)
.skip(2)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(3)
next(4)
next(5)
completed
Observable.create { (observer) -> Disposable in
var i = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
print("原始序列发射数据: ",i,"time: ",Date())
if i <= 5{
observer.onNext(i)
}else{
observer.onCompleted()
timer.invalidate()
}
i = i+1
})
return Disposables.create()
}
.skip(2.5, scheduler: MainScheduler.instance)
.subscribe{print("接收到数据: ",$0," time: ",Date())}
.disposed(by: GlobalDisposeBag)
输出:
原始序列发射数据: 1 time: 2018-03-23 04:24:45 +0000
原始序列发射数据: 2 time: 2018-03-23 04:24:46 +0000
原始序列发射数据: 3 time: 2018-03-23 04:24:47 +0000
接收到数据: next(3) time: 2018-03-23 04:24:47 +0000
原始序列发射数据: 4 time: 2018-03-23 04:24:48 +0000
接收到数据: next(4) time: 2018-03-23 04:24:48 +0000
原始序列发射数据: 5 time: 2018-03-23 04:24:49 +0000
接收到数据: next(5) time: 2018-03-23 04:24:49 +0000
原始序列发射数据: 6 time: 2018-03-23 04:24:50 +0000
接收到数据: completed time: 2018-03-23 04:24:50 +0000
Observable.of(1, 2, 3, 4, 1, 2, 3)
.skipWhile { $0 < 4 }
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(4)
next(1)
next(2)
next(3)
completed
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.skipUntil(referenceSequence)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext(1)
sourceSequence.onNext(2)
sourceSequence.onNext(3)
print("参照序列发射元素")
referenceSequence.onNext("?")
sourceSequence.onNext(4)
sourceSequence.onNext(5)
sourceSequence.onNext(6)
输出:
参照序列发射元素
next(4)
next(5)
next(6)
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.skipUntil(referenceSequence)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext(1)
sourceSequence.onNext(2)
sourceSequence.onNext(3)
print("参照序列异常终止")
referenceSequence.onError(ExampleError)
sourceSequence.onNext(4)
sourceSequence.onNext(5)
sourceSequence.onNext(6)
输出:
参照序列异常终止
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let sourceSequence = PublishSubject()
let referenceSequence = PublishSubject()
sourceSequence
.skipUntil(referenceSequence)
.subscribe{ print($0) }
.disposed(by: GlobalDisposeBag)
sourceSequence.onNext(1)
sourceSequence.onNext(2)
sourceSequence.onNext(3)
print("参照序列正常终止")
referenceSequence.onCompleted()
sourceSequence.onNext(4)
sourceSequence.onNext(5)
sourceSequence.onNext(6)
输出:
参照序列正常终止
let sourceSeq = Observable.create { (observer) -> Disposable in
var i = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if i <= 10{
print("原始序列发射数据:\(i) [第 \(i) 秒]")
observer.onNext(i)
}else{
observer.onCompleted()
timer.invalidate()
}
i = i+1
})
return Disposables.create()
}
let samplerSeq = Observable.create { (observer) -> Disposable in
var i = 1
Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { (timer) in
if i <= 3{
let item = String(i)+"SamplerItem"
print("采样序列发射数据:\(item)")
observer.onNext(item)
}else{
observer.onCompleted()
timer.invalidate()
}
i = i+1
})
return Disposables.create()
}
sourceSeq.sample(samplerSeq).subscribe{print("观察者接收:",$0)}.disposed(by: GlobalDisposeBag)
输出:
原始序列发射数据:1 [第 1 秒]
原始序列发射数据:2 [第 2 秒]
原始序列发射数据:3 [第 3 秒]
采样序列发射数据:1SamplerItem
订阅者接收到数据: next(3)
原始序列发射数据:4 [第 4 秒]
原始序列发射数据:5 [第 5 秒]
采样序列发射数据:2SamplerItem
订阅者接收到数据: next(5)
订阅者接收到数据: completed
采样序列发射数据:3SamplerItem
Observable.create { (observer) -> Disposable in
var i = 0
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if i == 10{
print("原始序列终止: [第 \(i) 秒])")
observer.onCompleted()
timer.invalidate()
}else{
print("原始序列发射数据:\(i) [第 \(i) 秒])")
observer.onNext(i)
}
i = i+1
}).fire()
return Disposables.create()
}.throttle(2.5, latest: false,scheduler: MainScheduler.instance)
.subscribe({print("观察者接收",$0)})
.disposed(by: GlobalDisposeBag)
输出:
原始序列发射数据:0 [第 0 秒])
观察者接收 next(0)
原始序列发射数据:1 [第 1 秒])
原始序列发射数据:2 [第 2 秒])
原始序列发射数据:3 [第 3 秒])
观察者接收 next(3)
原始序列发射数据:4 [第 4 秒])
原始序列发射数据:5 [第 5 秒])
原始序列发射数据:6 [第 6 秒])
观察者接收 next(6)
原始序列发射数据:7 [第 7 秒])
原始序列发射数据:8 [第 8 秒])
原始序列发射数据:9 [第 9 秒])
观察者接收 next(9)
原始序列终止: [第 10 秒])
观察者接收 completed
Observable.create { (observer) -> Disposable in
var i = 0
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if i == 10{
print("原始序列终止: [第 \(i) 秒])")
observer.onCompleted()
timer.invalidate()
}else{
print("原始序列发射数据:\(i) [第 \(i) 秒])")
observer.onNext(i)
}
i = i+1
}).fire()
return Disposables.create()
}.throttle(2.5, scheduler: MainScheduler.instance)
.subscribe({print("订阅者接收",$0)})
.disposed(by: GlobalDisposeBag)
输出:
原始序列发射数据:0 [第 0 秒])
订阅者接收 next(0)
原始序列发射数据:1 [第 1 秒])
原始序列发射数据:2 [第 2 秒])
订阅者接收 next(2)
原始序列发射数据:3 [第 3 秒])
原始序列发射数据:4 [第 4 秒])
原始序列发射数据:5 [第 5 秒])
订阅者接收 next(5)
原始序列发射数据:6 [第 6 秒])
原始序列发射数据:7 [第 7 秒])
订阅者接收 next(7)
原始序列发射数据:8 [第 8 秒])
原始序列发射数据:9 [第 9 秒])
原始序列终止: [第 10 秒])
订阅者接收 next(9)
订阅者接收 completed
let subject = PublishSubject<Int>()
let dateFormatString = "HH:mm:ss.ms"
let debounceSeq = subject.debounce(1, scheduler: MainScheduler.instance)
debounceSeq.subscribe({print("观察者 received:",$0,"at time:",curDateString(dateFormatString))})
.disposed(by: GlobalDisposeBag)
print("call onNext 1 at time:",curDateString(dateFormatString))
subject.onNext(1)
print("call onNext 2 at time:",curDateString(dateFormatString))
subject.onNext(2)
print("call onNext 3 at time:",curDateString(dateFormatString))
subject.onNext(3)
delay(2) {
print("call onNext 4 at time:",curDateString(dateFormatString))
subject.onNext(4)
}
输出:
call onNext 1 at time: 12:36:55.3655
call onNext 2 at time: 12:36:55.3655
call onNext 3 at time: 12:36:55.3655
观察者 received: next(3) at time: 12:36:56.3656
call onNext 4 at time: 12:36:57.3657
观察者 received: next(4) at time: 12:36:58.3658
Observable.of(1, 2, 3)
.map { String($0)+"a" }
.subscribe({ print($0) })
.disposed(by: GlobalDisposeBag)
输出:
next(1a)
next(2a)
next(3a)
completed
代码部分详见Demo项目中的FlatMapDemoVC
代码部分详见Demo项目中的FlatMapLatestDemoVC
Observable.of(10, 100, 1000)
.scan(1) { aggregateValue, newValue in
print(aggregateValue, newValue)
return aggregateValue + newValue
}
.subscribe(onNext: { print("观察者接收到:",$0) })
.disposed(by: GlobalDisposeBag)
输出:
1 10
观察者接收到: 11
11 100
观察者接收到: 111
111 1000
观察者接收到: 1111
subject.buffer(timeSpan: 1, count: 3, scheduler: MainScheduler.instance)
.subscribe({print($0)}).disposed(by: GlobalDisposeBag)
subject.onNext(1)
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
//1、2、3会先输出,因为达到了 count 条件
//4会过一秒输出,因为达到 timeSpan 条件 (1,2,3输出后,缓冲区重置)
输出:
next([1, 2, 3])
next([4])
next([])
next([])
................
let subject = PublishSubject()
subject.buffer(timeSpan: 1, count: 3, scheduler: MainScheduler.instance)
.subscribe({print($0)}).disposed(by: GlobalDisposeBag)
subject.onNext(1)
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
subject.onError(ExampleError)
输出:
next([1, 2, 3])
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let subject = PublishSubject()
subject.buffer(timeSpan: 1, count: 3, scheduler: MainScheduler.instance)
.subscribe({print($0)}).disposed(by: GlobalDisposeBag)
subject.onNext(1)
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
subject.onCompleted()
输出:
next([1, 2, 3])
next([4])
completed
let subject = PublishSubject()
subject.window(timeSpan: 2, count: 3, scheduler: MainScheduler.asyncInstance)
.flatMap({ (seq) -> Observable in
print("接收到的最终序列的发射的数据(窗口 observable)",seq)
return seq
})
.subscribe({print($0)}).disposed(by: GlobalDisposeBag)
subject.onNext(1)
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
输出:
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
next(1)
next(2)
next(3)
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
next(4)
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
接收到的最终序列的发射的数据(窗口 observable) RxSwift.AddRef.Int>
.........
let groupSeq = Observable.of(-2,-20,0,14,21,34,55,62,73,80,90,92,100,102,150).groupBy { (score) -> String in
if score < 60 && score >= 0{
return "不及格"
}else if score >= 60 && score < 90{
return "良好"
}else if score >= 90 && score <= 100{
return "优秀"
}else{
return "invalid"
}
}.publish()
/* 筛选出分组序列 */
let bujigeSeq = groupSeq.filter({ (item: GroupedObservable) -> Bool in
if item.key.contains("不及格"){
return true
}
return false
}) .flatMap { (groupedSeq: GroupedObservable) -> Observable in
return groupedSeq.asObservable()
}
bujigeSeq.subscribe{print("不及格-观察者",$0)}.disposed(by: GlobalDisposeBag)
let lianghaoSeq = groupSeq.filter({ (item: GroupedObservable) -> Bool in
if item.key.contains("良好"){
return true
}
return false
}) .flatMap { (groupedSeq: GroupedObservable) -> Observable in
return groupedSeq.asObservable()
}
lianghaoSeq.subscribe{print("良好-观察者",$0)}.disposed(by: GlobalDisposeBag)
let youxiuSeq = groupSeq.filter({ (item: GroupedObservable) -> Bool in
if item.key.contains("优秀"){
return true
}
return false
}) .flatMap { (groupedSeq: GroupedObservable) -> Observable in
return groupedSeq.asObservable()
}
youxiuSeq.subscribe{print("优秀-观察者",$0)}.disposed(by: GlobalDisposeBag)
groupSeq.connect().disposed(by: GlobalDisposeBag)
输出:
不及格-观察者 next(0)
不及格-观察者 next(14)
不及格-观察者 next(21)
不及格-观察者 next(34)
不及格-观察者 next(55)
良好-观察者 next(62)
良好-观察者 next(73)
良好-观察者 next(80)
优秀-观察者 next(90)
优秀-观察者 next(92)
优秀-观察者 next(100)
不及格-观察者 completed
良好-观察者 completed
优秀-观察者 completed
let seq = Observable.create { (observer) -> Disposable in
var i = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
if i <= 4{
observer.onNext(i)
i = i+1
}else{
observer.onCompleted()
//如果是 error ,则不会发射元素,只会发射 error 事件。
}
}).fire()
return Disposables.create()
}.toArray()
print("开始订阅, time:", Date())
seq.subscribe{print("接收到数据: ",$0," time: ",Date())}.disposed(by: GlobalDisposeBag)
输出:
开始订阅, time: 2018-03-23 04:49:29 +0000
接收到数据: next([1, 2, 3, 4]) time: 2018-03-23 04:49:33 +0000
接收到数据: completed time: 2018-03-23 04:49:33 +0000
Observable.of(1, 2, 3).reduce("a", accumulator: { (aggregate, ele) -> String in
return aggregate + String(ele)
})
.subscribe{ print($0) }
.disposed(by: disposeBag)
输出:
next(a123)
completed
let disposeBag = DisposeBag()
let subject1 = PublishSubject.init()
let subject2 = PublishSubject.init()
Observable.concat(subject1,subject2).subscribe{print($0)}.disposed(by: disposeBag)
subject1.onNext("1")
subject1.onNext("2")
subject2.onNext("这个元素将不会输出")
subject1.onCompleted()
subject2.onNext("a")
subject2.onNext("b")
subject2.onCompleted()
输出:
next(1)
next(2)
next(a)
next(b)
completed
let disposeBag = DisposeBag()
let subject1 = PublishSubject.init()
let subject2 = PublishSubject.init()
Observable.concat(subject1,subject2).subscribe{print($0)}.disposed(by: disposeBag)
subject1.onNext("1")
subject1.onNext("2")
//即使此时最终序列还不接收 subject2 的发射数据,但是它的异常终止也会让最终序列异常终止。
subject2.onError(ExampleError)
subject1.onCompleted()
subject2.onNext("a")
subject2.onNext("b")
subject2.onCompleted()
输出:
next(1)
next(2)
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
//此时订阅后,并不会让序列发射元素
let seq = Observable.of(1,2,3).publish()
seq.subscribe{ print($0) }.disposed(by: DisposeBag())
没有输出
let seq = Observable.interval(1, scheduler: MainScheduler.instance).publish()
seq.subscribe{ print("观察者1:",$0) }.disposed(by: GlobalDisposeBag)
seq.connect().disposed(by: GlobalDisposeBag)
//后续的订阅会 shares single subscription
delay(3) {
seq.subscribe{ print("观察者2:",$0) }.disposed(by: GlobalDisposeBag)
}
//后续的订阅会 shares single subscription
delay(5) {
seq.subscribe{ print("观察者3:",$0) }.disposed(by: GlobalDisposeBag)
}
输出:
观察者1: next(0)
观察者1: next(1)
观察者1: next(2)
观察者1: next(3)
观察者2: next(3)
观察者1: next(4)
观察者2: next(4)
观察者1: next(5)
观察者2: next(5)
观察者3: next(5)
观察者1: next(6)
观察者2: next(6)
观察者3: next(6)
观察者1: next(7)
观察者2: next(7)
观察者3: next(7)
观察者1: next(8)
观察者2: next(8)
观察者3: next(8)
观察者1: next(9)
观察者2: next(9)
观察者3: next(9)
....................
let seq = Observable.interval(1, scheduler: MainScheduler.instance).replay(2)
seq.subscribe{ print("订阅者1 接收到数据:",$0) }.disposed(by: GlobalDisposeBag)
seq.connect().disposed(by: GlobalDisposeBag)
delay(3) {
seq.subscribe{ print("订阅者2 接收到数据:",$0) }.disposed(by: GlobalDisposeBag)
}
//会接收到订阅前发射的最近3个元素
delay(5) {
seq.subscribe{ print("订阅者3 接收到数据",$0) }.disposed(by: GlobalDisposeBag)
}
输出:
订阅者1 接收到数据: next(0)
订阅者1 接收到数据: next(1)
订阅者1 接收到数据: next(2)
订阅者2 接收到数据: next(1)
订阅者2 接收到数据: next(2)
订阅者1 接收到数据: next(3)
订阅者2 接收到数据: next(3)
订阅者1 接收到数据: next(4)
订阅者2 接收到数据: next(4)
订阅者3 接收到数据 next(3)
订阅者3 接收到数据 next(4)
订阅者1 接收到数据: next(5)
订阅者2 接收到数据: next(5)
订阅者3 接收到数据 next(5)
订阅者1 接收到数据: next(6)
订阅者2 接收到数据: next(6)
订阅者3 接收到数据 next(6)
订阅者1 接收到数据: next(7)
订阅者2 接收到数据: next(7)
订阅者3 接收到数据 next(7)
.............................
let seq = Observable.interval(1, scheduler: MainScheduler.instance).replayAll()
seq.subscribe{ print("订阅1:",$0) }.disposed(by: GlobalDisposeBag)
seq.connect().disposed(by: GlobalDisposeBag)
delay(3) {
seq.subscribe{ print("订阅2:",$0) }.disposed(by: GlobalDisposeBag)
}
delay(5) {
seq.subscribe{ print("订阅3:",$0) }.disposed(by: GlobalDisposeBag)
}
输出:
订阅1: next(0)
订阅1: next(1)
订阅1: next(2)
订阅2: next(0)
订阅2: next(1)
订阅2: next(2)
订阅1: next(3)
订阅2: next(3)
订阅1: next(4)
订阅2: next(4)
订阅3: next(0)
订阅3: next(1)
订阅3: next(2)
订阅3: next(3)
订阅3: next(4)
订阅1: next(5)
订阅2: next(5)
订阅3: next(5)
..............
let subject = PublishSubject()
_ = subject
.subscribe{ print("Subject 观察者: \($0)") }
let intSequence = Observable
.interval(1, scheduler: MainScheduler.instance)
.multicast(subject)
intSequence.subscribe{ print("\tintSequence观察者 1:, Event: \($0)") }.disposed(by: GlobalDisposeBag)
intSequence.subscribe{ print("\tintSequence观察者 2:, Event: \($0)") }.disposed(by: GlobalDisposeBag)
intSequence.subscribe{ print("\tintSequence观察者 3:, Event: \($0)") }.disposed(by: GlobalDisposeBag)
//2秒后开始发射数据
delay(2) { intSequence.connect().disposed(by: GlobalDisposeBag)}
//subject,5 秒后终止
delay(5) {
subject.onCompleted()
}
输出:
Subject 观察者: next(0)
intSequence观察者 1:, Event: next(0)
intSequence观察者 2:, Event: next(0)
intSequence观察者 3:, Event: next(0)
Subject 观察者: next(1)
intSequence观察者 1:, Event: next(1)
intSequence观察者 2:, Event: next(1)
intSequence观察者 3:, Event: next(1)
Subject 观察者: completed
intSequence观察者 1:, Event: completed
intSequence观察者 2:, Event: completed
intSequence观察者 3:, Event: completed
let sequenceThatFails = PublishSubject()
sequenceThatFails
.catchErrorJustReturn("Catch it")
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
sequenceThatFails.onNext("1")
sequenceThatFails.onNext("2")
sequenceThatFails.onError(ExampleError)
sequenceThatFails.onNext("3")
sequenceThatFails.onNext("4")
输出:
next(1)
next(2)
next(Catch it)
completed
let sequenceThatFails = PublishSubject()
let recoverySequence = PublishSubject()
sequenceThatFails
.catchError {_ in
return recoverySequence
}
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
sequenceThatFails.onNext("1")
sequenceThatFails.onNext("2")
sequenceThatFails.onNext("3")
sequenceThatFails.onNext("4")
sequenceThatFails.onError("Some Error")
recoverySequence.onNext("r3")
recoverySequence.onNext("r4")
输出:
next(1)
next(2)
next(3)
next(4)
next(r3)
next(r4)
var count = 1
let sequenceThatErrors = Observable.create { observer in
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
if count == 1 {
observer.onError(ExampleError)
count += 1
}
observer.onNext("4")
observer.onNext("5")
observer.onNext("6")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.retry()
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)
completed
let sequenceThatErrors = Observable.create { observer in
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
observer.onError(ExampleError)
observer.onNext("4")
observer.onNext("5")
observer.onNext("6")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.retry(3)
.subscribe { print($0) }
.disposed(by: GlobalDisposeBag)
输出:
next(1)
next(2)
next(3)
next(1)
next(2)
next(3)
next(1)
next(2)
next(3)
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let notifyer = PublishSubject()
var count = 1
let sequenceThatErrors = Observable.create { observer in
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
if count == 1{
observer.onError("Some Error")
count = count + 1
}
observer.onNext("4")
observer.onNext("5")
observer.onNext("6")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.retryWhen({ (errorSeq:Observable) -> Observable in
return notifyer
})
.subscribe { print("接收到数据: ",$0," time: ",Date()) }
.disposed(by: GlobalDisposeBag)
delay(2) {
print("通知序列发射元素, time: ", Date())
notifyer.onNext("a")
//notifyer.onCompleted() //以 Completed 事件结束
//notifyer.onError("Some Error") // 以 error 事件结束
输出:
接收到数据: next(1) time: 2018-03-23 05:10:18 +0000
接收到数据: next(2) time: 2018-03-23 05:10:18 +0000
接收到数据: next(3) time: 2018-03-23 05:10:18 +0000
通知序列发射元素, time: 2018-03-23 05:10:20 +0000
接收到数据: next(1) time: 2018-03-23 05:10:20 +0000
接收到数据: next(2) time: 2018-03-23 05:10:20 +0000
接收到数据: next(3) time: 2018-03-23 05:10:20 +0000
接收到数据: next(4) time: 2018-03-23 05:10:20 +0000
接收到数据: next(5) time: 2018-03-23 05:10:20 +0000
接收到数据: next(6) time: 2018-03-23 05:10:20 +0000
接收到数据: completed time: 2018-03-23 05:10:20 +0000
//设置序列的订阅逻辑该如何调度
let seq1 = PublishSubject()
let seq2 = PublishSubject()
let seq3 = PublishSubject()
let ambSeq = seq1.amb(seq2).amb(seq3)
ambSeq.subscribe{print($0)}.disposed(by: GlobalDisposeBag)
//序列2 先发射,则 ambSeq 只会发射序列2的数据
seq2.onNext("seq2_first")
seq1.onNext("seq1_a")
seq1.onNext("seq1_b")
seq2.onNext("seq2_a")
seq2.onNext("seq2_b")
seq3.onNext("seq3_a")
seq3.onNext("seq3_b")
输出:
next(seq2_first)
next(seq2_a)
next(seq2_b)
let seq1 = PublishSubject()
seq1.ifEmpty(default: "placeholder")
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
seq1.onNext("item1")
seq1.onCompleted()
输出:
next(item1)
completed
let seq1 = PublishSubject()
seq1.ifEmpty(default: "placeholder")
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
seq1.onCompleted()
输出:
next(placeholder)
completed
let seq1 = PublishSubject()
seq1.ifEmpty(default: "placeholder")
.subscribe{print($0)}
.disposed(by: GlobalDisposeBag)
seq1.onError(ExampleError)
输出:
error(Error Domain=RxExampleError Code=0 "(null)" UserInfo={msg=这是一个示例错误})
let sourceSeq = PublishSubject()
let standbySeq = PublishSubject()
sourceSeq.ifEmpty(switchTo: standbySeq).subscribe{print($0)}.disposed(by: GlobalDisposeBag)
sourceSeq.onCompleted()
standbySeq.onNext("备用队列 item1")
standbySeq.onCompleted()
输出:
next(备用队列 item1)
completed