一、创建观察者Observer<?>
使用subscribe来创建观察者
// observable是一个可监听序列
observable.subscribe(onNext: { (value) in
print(value)
}).dispose()
二、AnyObserver任意观察者
AnyObserver可当做任意观察者,观察任意的可监听队列
let observable = Observable<Int>.create { (observer) -> Disposable in
observer.onNext(1)
observer.onNext(2)
observer.onNext(4)
observer.onCompleted()
return Disposables.create()
}
let anyObserver: AnyObserver<Int> = AnyObserver { (event) in
switch (event) {
case .next(let value):
print(value)
case .completed:
print("complete")
case .error(let err):
print(err)
}
}
observable.subscribe(anyObserver).dispose()
网友评论