备注:本文参考自田腾飞博文 [RxSwift入坑解读-你所需要知道的各种概念] (http://www.codertian.com/2016/11/27/RxSwift-ru-keng-ji-read-document/),出于个人学习以及笔记需要特记录下RxSwift基本使用
概念
Observable : 可被观察的,事件源
Observer : 观察者,观察者需要订阅Observable,才能受到其发出的事件
DisposeBag : 相当于iOS中的ARC,会在适当的时候销毁观察者,自动去释放资源
如果需要手动销毁观察者直接调用dispose()方法,例:
Observable.empty().subscribe { (str:Event) in
print(“empty:”,str)
}.dispose()
subscribe : 订阅者,用于订阅sequence发出的事件
基本使用
never
never就是创建一个sequence,但不发出任何事件信号
let bag = DisposeBag()
Observable.never().subscribe { (str :Event<String>) in
print("never:",str) //无
}.addDisposableTo(bag)
备注:为了方便简洁,后续例子中创建bag变量的代码将省略
empty
empty创建一个空的sequence,但只能发出一个completed事件
Observable.empty().subscribe { (str :Event<String>) in
print("empty:",str)
}.addDisposableTo(bag)
//empty: completed
just
just创建一个sequence,但只能发出一种特定的事件,能正常结束
Observable.just("just").subscribe { (str :Event<String>) in
print("just:",str)
}.addDisposableTo(bag)
//just:next(just)
//just:completed
of
创建一个sequence能发出很多种事件信号
Observable.of("1","2","3").subscribe { (str) in
print("of:",str)
}.addDisposableTo(bag)
/**
of: next(1)
of: next(2)
of: next(3)
of: completed
*/
//subscribe onNext 直接取值
Observable.of("1","2","3").subscribe(onNext: { (str) in
print("of2:",str)
}).addDisposableTo(bag)
/**
of2: 1
of2: 2
of2: 3
*/
from
from从集合中创建sequence,例如数组,字典或者Set
Observable.from([10,100,1000]).subscribe(onNext: { (num) in
print("from:",num)
}).addDisposableTo(bag)
/**
from: 10
from: 100
from: 1000
**/
create
create 自定义可观察的sequence
//create 自定义可观察的sequence
let myObservable = Observable.create { (observer:AnyObserver<Any>) -> Disposable in
observer.onNext("12")
observer.onNext("21")
observer.onNext("123")
observer.onCompleted()
return Disposables.create()
}
myObservable.subscribe { (e:Event<Any>) in
print("myObservable:",e)
}.addDisposableTo(bag)
/**
myObservable: next(12)
myObservable: next(21)
myObservable: next(123)
myObservable: completed
**/
range
range 创建一个sequence,会发出这个范围中所有事件
Observable.range(start: 1, count: 5).subscribe(onNext: { (num) in
print("range:",num)
}).addDisposableTo(bag)
/**
range: 1
range: 2
range: 3
range: 4
range: 5
**/
repeatElement
创建一个sequence,发出特定的事件n次
Observable.repeatElement("LouKit").take(3).subscribe { print($0)}.addDisposableTo(bag)
//重复发出3次,如果没有take 就无限次
/**
next(LouKit)
next(LouKit)
next(LouKit)
completed
**/
generate
generate是创建一个可观察sequence,当初始化的条件为true的时候,他就会发出所对应的事件
Observable.generate(initialState: 10, condition: {$0 < 15}, iterate: {$0 + 1}).subscribe(onNext: {print("generate",$0)}).addDisposableTo(bag)
/**
generate 10
generate 11
generate 12
generate 13
generate 14
**/
deferred
deferred会为每一为订阅者observer创建一个新的可观察序列
var index = 1
let deferred = Observable<String>.deferred{
print("index:",index)
index += 1
return Observable.create{ observer in
observer.onNext("1")
observer.onNext("2")
observer.onCompleted()
return Disposables.create()
}
}
deferred.subscribe { print("调用1:",$0)}.addDisposableTo(bag)
deferred.subscribe { print("调用2:",$0)}.addDisposableTo(bag)
/**
index: 1
调用1: next(1)
调用1: next(2)
调用1: completed
index: 2
调用2: next(1)
调用2: next(2)
调用2: completed
**/
do
主要用于在subscribe中onNext,onError,onCompleted前调用
Observable.just("00").do(onNext: {print("doOnNext:",$0)},onError: {print("doOnError:",$0)},onCompleted: {print("doOnCompleted:")})
.subscribe(onNext: { (str) in
print("onNext:",str)
}, onError: { (error) in
print("onError")
}, onCompleted: {
print("onCompleted")
}).addDisposableTo(bag)
/**
doOnNext: 00
onNext: 00
doOnCompleted:
onCompleted
**/
Subjects
Subjet是observable和Observer之间的桥梁,一个Subject既可以充当Obserable也可以充当Observer,即它可以发出事件,也可以监听事件
PublishSubject
采用PublishSubject订阅事件的时候,只能接收到订阅他之后
发生的事件
let publicSubject = PublishSubject<String>()
publicSubject.onNext("A")
publicSubject.onNext("B")
publicSubject.subscribe(onNext: {print("publicSubject:",$0)}) .addDisposableTo(bag)
publicSubject.onNext("C")
publicSubject.onNext("D")
/**
publicSubject: C
publicSubject: D
**/
ReplaySubject
可以接收到订阅他之后以及之前
发生的事件,对于要接受几个以前的事件取决于bufferSize设置的大小
let replaySubject = ReplaySubject<String>.create(bufferSize: 2)
replaySubject.onNext("A")
replaySubject.onNext("B")
replaySubject.onNext("C")
replaySubject.onNext("D")
replaySubject.subscribe(onNext: {print("replaySubject:",$0)}) .addDisposableTo(bag)
replaySubject.onNext("E")
replaySubject.onNext("F")
replaySubject.onNext("G")
/**
replaySubject: C
replaySubject: D
replaySubject: E
replaySubject: F
replaySubject: G
**/
//接受全部的事件
let replaySubject2 = ReplaySubject<String>.createUnbounded()
replaySubject2.onNext("A")
replaySubject2.onNext("B")
replaySubject2.subscribe(onNext: {print("replaySubject2:",$0)}) .addDisposableTo(bag)
replaySubject2.onNext("E")
replaySubject2.onNext("F")
/**
replaySubject2: A
replaySubject2: B
replaySubject2: E
replaySubject2: F
**/
BehaviorSubject
采用BehaviorSubject订阅事件,会接收到订阅之前的最后一个事件
以及订阅之后所有事件
。
let behavior = BehaviorSubject(value: "behavior")
behavior.onNext("A")
behavior.onNext("B")
behavior.subscribe(onNext: {print("behavior:",$0)}).addDisposableTo(bag)
behavior.onNext("C")
behavior.onNext("D")
/**
behavior: B
behavior: C
behavior: D
**/
Variable
Variable是对BehaviorSubject一个包装;
Variable当成Obserable, 让订阅者进行订阅时, 需要asObserable转成Obserable;
Variable发出事件, 直接修改对象的value即可;
当事件结束时,Variable会自动发出completed事件
let variable = Variable("variable")
variable.value = "A"
variable.value = "B"
variable.asObservable().subscribe { (event:Event<String>) in
print("variable:",event)
}.addDisposableTo(bag)
variable.value = "C"
variable.value = "D"
/**
variable: next(B)
variable: next(C)
variable: next(D)
variable: completed
**/
联合操作
联合操作就是把多个Observable流合成单个Observable流
startWith
在发出事件消息之前,先发出某个特定的事件消息。
Observable.of(1,2).startWith(3).subscribe(onNext: {print($0)}).addDisposableTo(bag)
/**
3
1
2
**/
merge
将多个Observable流合成单个Observable流,然后任何一个Observable
发出事件都能被接收到
let sub1 = PublishSubject<String>()
let sub2 = PublishSubject<String>()
Observable.of(sub1,sub2).merge().subscribe(onNext: { print($0) }).addDisposableTo(bag)
sub1.onNext("sub1-1")
sub1.onNext("sub1-2")
sub2.onNext("sub2-1")
sub1.onNext("sub1-2")
sub2.onNext("sub2-2")
/**
sub1-1
sub1-2
sub2-1
sub1-2
sub2-2
**/
zip
将多个Observable流合成单个Observable流,只有当多个Observable流同时
发出事件时,并且把多个Observable流的内容
合并成一个元组
,才会触发压缩流的事件。
let zip1 = PublishSubject<String>()
let zip2 = PublishSubject<String>()
Observable.zip(zip1,zip2){ zip1,zip2 in
"\(zip1) \(zip2)"
}.subscribe(onNext: { print($0) })
.addDisposableTo(bag)
zip1.onNext("zip1-1")
zip1.onNext("zip1-2")
zip2.onNext("zip2-1")
zip2.onNext("zip2-2")
/**
zip1-1 zip2-1
zip1-2 zip2-2
**/
注意:merge、zip都能将多个Observable流合成单个Observable流,但合并后前者任何一个Observable发出事件都能被接收到,后者必须是多个流同时发出事件时才被接收到
combineLatest
将多个Observable流合并起来 并拿到其各个流的最新值,即每个合并的signal至少
都有过一次onNext
,才会触发合并的流
let ps1 = PublishSubject<String>()
let ps2 = PublishSubject<String>()
Observable.combineLatest(ps1, ps2) { element1, element2 in
"\(element1) \(element2)"
}
.subscribe(onNext: { print($0) })
.addDisposableTo(bag)
ps1.onNext("ps1-01")
ps1.onNext("ps1-02")
ps2.onNext("ps2-01")
/**
ps1-02 ps2-01
**/
switchLatest
用于对事件流进行转换,即一个Observable中的内容还是Observable。(个人理解)
let bs1 = BehaviorSubject(value: "1")
let bs2 = BehaviorSubject(value: "A")
let variable = Variable(bs1)
variable.asObservable().switchLatest().subscribe(onNext: {print($0)}).addDisposableTo(bag)
bs1.onNext("2")
variable.value = bs2
bs1.onNext("3")
bs2.onNext("B")
/**
1
2
A
B
**/