never
never就是创建一个sequence,但是不发出任何事件信号。
let disposeBag: DisposeBag()
let neverObservable = Observable<String>.never()
neverObservable.subscribe { (event:Event<String>) in
print(event.element ?? "")
}.disposed(by: disposeBag)
结果是什么都不打印
empty
empty就是创建一个空的sequence,只能发出一个completed事件
let disposeBag: DisposeBag()
let emptyObservable = Observable<String>.empty()
emptyObservable.subscribe { (event:Event<String>) in
print(event)
}.disposed(by: disposeBag)
completed
just
just是创建一个sequence只能发出一种特定的事件,能正常结束
let disposeBag: DisposeBag()
let justObservable = Observable.just("justObservable")
justObservable { (event:Event<String>) in
print(event)
}.disposed(by: disposeBag)
next(justObservable)
completed
of
of是创建一个sequence能发出很多种事件信号
let disposeBag: DisposeBag()
let ofObservable = Observable.of("1","2","3","4")
ofObservable.subscribe { (event:Event<String>) in
print(event)
}.disposed(by: disposeBag)
next(1)
next(2)
next(3)
next(4)
completed
from
from就是从集合中创建sequence,例如数组,字典或者Set
let disposeBag: DisposeBag()
let fromObservable = Observable.from(["a":"1","b":"2"])
fromObservable.subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
next((key: "b", value: "2"))
next((key: "a", value: "1"))
completed
create
我们也可以自定义可观察的sequence,那就是使用create
let disposeBag: DisposeBag()
let creatObservable = Observable.create { (observer:AnyObserver<Any>) -> Disposable in
observer.onNext("123")
observer.onNext(1.44)
observer.onCompleted()
return Disposables.create()
}
creatObservable.subscribe { (event:Event<Any>) in
print(event)
}.disposed(by: disposeBag)
next(123)
next(1.44)
completed
range
range就是创建一个sequence,他会发出这个范围中的从开始到结束的所有事件
let disposeBag: DisposeBag()
let rangeObservable = Observable.range(start: 1, count: 10)
rangeObservable.subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)
next(7)
next(8)
next(9)
next(10)
completed
repeatElement
创建一个sequence,发出特定的事件n次
let disposeBag: DisposeBag()
let repeatElementObservable = Observable.repeatElement("repeatElement")
repeatElementObservable.take(4).subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
next(repeatElement)
next(repeatElement)
next(repeatElement)
next(repeatElement)
completed
网友评论