使用一个函数从头创建一个Observable
/// 创建可观察对象
let id = Observable.create { observer in
observer.onNext(0)
observer.onNext(1)
observer.onNext(2)
observer.onNext(3)
observer.onNext(4)
observer.onCompleted()
return Disposables.create()
}
/// 订阅可观察对象
id.subscribe(onNext: { id in
print(id)
}, onCompleted: {
print("completed")
})
创建一个只产生唯一一个元素的 Observable
let justID = Observable.just(0)
/// 等价于
let justID1 = Observable.create { (observer) -> Disposable in
observer.onNext(0)
observer.onCompleted()
return Disposables.create()
}
将其他类型或者数据结构转换为 Observable
/// eg: 1 将一个数组转换为 Observable
let numbers = Observable.from([0, 1, 2])
/// 等价于
let numbers1 = Observable.create { (observer) -> Disposable in
observer.onNext(0)
observer.onNext(1)
observer.onNext(2)
observer.onCompleted()
return Disposables.create()
}
/// eg: 2 将一个可选值转换为 Observable
let optional: String? = nil
let value = Observable.from(optional: optional)
/// 等价于
let optional1 = Observable.create { (observer) -> Disposable in
if let element = optional {
observer.onNext(element)
}
observer.onCompleted()
return Disposables.create()
}
创建一个重复发出某个元素的 Observable
let repeatID = Observable.repeatElement(666)
repeatID.subscribe(onNext: { element in
print(element)
})
该方法创建一个只有当提供的所有的判断条件都为 true 的时候,才会给出动作的 Observable 序列
let generateID = Observable.generate(initialState: 0,
condition: { $0 <= 10},
iterate: { $0 + 2 })
/// 等价于: 使用of()方法
let generateIDs = Observable.of(0, 2, 4, 6, 8, 10)
generateID.subscribe(onNext: { (num) in
print(num)
})
只有当订阅者订阅才创建Observable;为每个订阅创建一个新的Observable
let deferID = Observable.deferred { () -> Observable in
return Observable.create({ observer in
observer.onNext(666)
observer.onCompleted()
return Disposables.create()
})
}
创建一个发射特定整数序列的 Observable
let rangeID = Observable.range(start: 0, count: 10)
rangeID.subscribe(onNext: { (num) in
print(num)
}, onCompleted: {
print("completed")
})
创建一个按照给定的时间间隔发射整数序列的Observable
Interval操作符返回一个Observable,它按固定的时间间隔发射一个无限递增的整数序列
let interval = Observable.interval(1, scheduler: MainScheduler.instance)
interval.subscribe ({ event in
print(event)
})
创建一个 Observable 在一段延时后,产生唯一的一个元素
let timerID = Observable.timer(1, scheduler: MainScheduler.instance)
timerID.subscribe(onNext: { (num) in
print(num)
})
创建一个只有一个完成事件的 Observable
let emptyId = Observable.empty()
/// 等价于
let emptyId1 = Observable.create { observer -> Disposable in
observer.onCompleted()
return Disposables.create()
}
创建一个只有 error 事件的 Observable
enum MyError: Error {
case A
case B
}
let observable = Observable<Int>.error(MyError.A)
创建一个不发射任何数据的Observable
let neverID = Observable.never()
/// 等价于
let neverID2 = Observable.create { (observer) -> Disposable in
return Disposables.create()
}