func creatObservable(){
//just - 只包含一个事件的序列
_ = Observable.just("111").subscribe{
(evevt:RxSwift.Event<String>) -> Void in
print(evevt)
}
//of - 包含固定个数事件的序列
_ = Observable.of(0,1,2,3,4)
.subscribe({
(evevt: RxSwift.Event<Int>) -> Void in
print(evevt)
})
// error - 只产生.Error事件的序列
let err = NSError(domain: "Test", code: -1, userInfo: nil)
_ = Observable<Int>.error(err)
.subscribe({
(event: RxSwift.Event<Int>) in
print(event)
})
//调用创建的自定义事件
myJust(10).subscribe{
print($0)
}
myJust(5).subscribe {
print($0)
}
//generate - 用prev决定next的事件序列
_ = Observable.generate(
initialState: 0,
condition: {$0 < 10},
iterate: {$0 + 1})
.subscribe{
print($0)
}
//deferred - 只有在被订阅后才创建并产生事件的序列
let deferredSequence = Observable<Int>.deferred {
print("generating")
return Observable.generate(
initialState: 0,
condition: { $0 < 3 },
iterate: { $0 + 1})
}
//当我们订阅deferredSequence时:
_ = deferredSequence.subscribe { print($0) }
_ = deferredSequence.subscribe { print($0) }
}
//create - 自定义的事件序列
func myJust(event: Int) -> Observable<Int> {
return Observable.create { observer in
if event % 2 == 0 {
observer.on(.Next(event))
observer.on(.Completed)
}else {
let err = NSError(domain: "不符合条件", code: 1000, userInfo: nil)
observer.on(.Error(err))
}
return NopDisposable.instance
}
}
几种常见的Observables创建方法
最新推荐文章于 2020-01-27 21:46:56 发布