一、创建可监听序列
能发出三种结果
- 发出元素onNext(可发出多次)
- 发出完成事件onCompleted
- 发出异常事件onErrorr
let observable = Observable<Int>.create { (observer) -> Disposable in
observer.onNext(1)
observer.onNext(2)
observer.onNext(4)
observer.onCompleted()
return Disposables.create()
}
observable.subscribe(onNext: { (value) in
print(value)
}).dispose()
二、signle
能发出两种事件
- 发出元素success(只能发出一次)
- 发出异常时间error
let single = Single<Int>.create { (observer) -> Disposable in
observer(.success(1))
return Disposables.create()
}
single.subscribe(onSuccess: { (value) in
print(value)
}, onError: { (_) in
}).dispose()
三、Completable
能发出两种事件
- 发出完成事件onCompleted
- 发出异常事件onErrorr
let completeable = Completable.create { (observer) -> Disposable in
observer(.completed)
return Disposables.create()
}
completeable.subscribe(onCompleted: {
print("success")
}, onError: { (_) in
print("error")
}).dispose()
四、Maybe
只能发出一种时间
- 元素 或者 completed 或者 error(三者任取其一)
let maybe = Maybe<Int>.create { (observer) -> Disposable in
observer(.success(0))
return Disposables.create()
}
maybe.subscribe(onSuccess: { (value) in
print(value)
}, onError: { (_) in
print("error")
}, onCompleted: {
print("complete")
}).dispose()
网友评论