Observable和Observer
理解了观察者模式这两个概念就很好理解了,Observable就是可被观察的,也就是我们说的宝宝,他也是事件源。而Observer就是我们的观察者,也就是当收到事件的时候去做某些处理的爸爸妈妈。观察者需要去订阅(subscribe)被观察者,才能收到Observable的事件通知消息。
创建和订阅被观察
下面创建被观察者其实就是创建一个Obserable的sequence,就是创建一个流,然后就可以被订阅subscribe,这样被观察者发出时间消失,我们就能做相应的处理。
DisposeBag
相当于iOS中的ARC似得,会在适当的时候销毁观察者,相当于内存管理者吧。
subscribe
subscribe是订阅sequence发出的事件,比如next事件,error事件等。而subscribe(onNext:)是监听sequence发出的next事件中的element进行处理,他会忽略error和completed事件。相对应的还有subscribe(onError:) 和 subscribe(onCompleted:)
常见的几种sequence
never
创建一个sequence,但是不发出任何事件信号。
code:
let disposeBag = DisposeBag()
let neverSequence = Observable.never()
let neverSequenceSubscription = neverSequence.subscribe { _ in
print("This will never be printed")
}.disposed(by: disposeBag)
result:
什么都不打印
empty
创建一个空的sequence,只能发出一个completed事件
code:
let disposeBag = DisposeBag()
Observable.empty()
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
result:
completed
just
创建一个sequence只能发出一种特定的事件,能正常结束。
Code:
let disposeBag = DisposeBag()
Observable.just(":red_circle:")
.subscribe { event in
print(event)
}
.disposed(by: disposeBag)
Result:
next(:red_circle:)
completed
of
of是创建一个sequence能发出很多种事件信号。
Code:
let disposeBag = DisposeBag()
Observable.of(":dog:", ":cat:", ":mouse:", ":hamster:")
.subscribe(onNext: { element in
print(element)
})
.disposed(by: disposeBag)
Result:
:dog:
:cat:
:mouse:
:hamster:
如果把上面的onNext:去掉的话,结果会是这样子,也正好对应了我们subscribe中,subscribe只监听事件。
next(:dog:)
next(:cat:)
next(:mouse:)
next(:hamster:)
completed
from
from就是从集合中创建sequence,例如数组,字典或者Set.
Code:
let disposeBag = DisposeBag()
Observable.from([":dog:", ":cat:", ":mouse:", ":hamster:"])
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Result:
:dog:
:cat:
:mouse:
:hamster:
create
create用于自定义可观察的sequence。
Code:
let disposeBag = DisposeBag()
let myJust = { (element: String) -> Observable in
return Observable.create { observer in
observer.on(.next(element))
observer.on(.completed)
return Disposables.create()
}
}
myJust(":red_circle:")
.subscribe{ print($0) }
.disposed(by: disposeBag)
Result:
next(:red_circle:)
completed
range
range就是创建一个sequence,他会发出这个范围中的从开始到结束的所有事件。
Code:
let disposeBag = DisposeBag()
Observable.range(start: 1, count: 5)
.subscribe{ print($0) }
.disposed(by: disposeBag)
Result:
next(1)
next(2)
next(3)
next(4)
next(5)
completed
repeatElement
创建一个sequence,发出特定的事件n次
Code:
let disposeBag = DisposeBag()
Observable.repeatElement(":red_circle:")
.take(3)
.subscribe(onNext:{ print($0) })
.disposed(by: disposeBag)
Result:
:red_circle:
:red_circle:
:red_circle:
generate
generate是创建一个可观察sequence,当初始化的条件为true的时候,他就会发出所对应的事件
Code:
Observable.generate(initialState: 0, condition: { $0 < 3 }, iterate: { $0 + 1 })
.subscribe(onNext:{ print($0) })
.disposed(by: disposeBag)
Result:
0
1
2
deferred
deferred会为每一为订阅者observer创建一个新的可观察序列
Code:
let disposeBag = DisposeBag()
var count = 1
let deferredSequence = Observable.deferred {
print("Creating \(count)")
count += 1
return Observable.create { observer in
print("Emitting...")
observer.onNext(":dog:")
observer.onNext(":cat:")
observer.onNext(":monkey_face:")
return Disposables.create()
}
}
deferredSequence
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
deferredSequence
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Result:
Creating 1
Emitting...
:dog:
:cat:
:monkey_face:
Creating 2
Emitting...
:dog:
:cat:
:monkey_face:
error
创建一个可观察序列,但不发出任何正常的事件,只发出error事件并结束
Code:
let disposeBag = DisposeBag()
Observable.error(TestError.test)
.subscribe { print($0) }
.disposed(by: disposeBag)
Result:
error(test)
doOn
doOn我感觉就是在直接onNext处理时候,先执行某个方法,doOnNext( :)方法就是在subscribe(onNext:)前调用,doOnCompleted( :)就是在subscribe(onCompleted:)前面调用的。
Code:
let disposeBag = DisposeBag()
Observable.of(":apple:", ":pear:", ":tangerine:", ":lemon:")
.do(
onNext: { print("Intercepted:", $0) },
onError: { print("Intercepted error:", $0) },
onCompleted: { print("Completed") })
.subscribe(
onNext: { print($0) },
onCompleted: { print("结束") })
.disposed(by: disposeBag)
Result:
Intercepted: :apple:
:apple:
Intercepted: :pear:
:pear:
Intercepted: :tangerine:
:tangerine:
Intercepted: :lemon:
:lemon:
Completed
结束