never
never就是创建一个sequence,但是不发出任何事件信号
let disposeBag = DisposeBag ()
let neverSequence = Observable <String >.never()
let neverSequenceSubscription = neverSequence
.subscribe ({ _ in
print ("This will never be printed" )
}).disposed(by: disposeBag)
复制代码
empty
empty就是创建一个空的sequence,只能发出一个completed事件
let disposeBag = DisposeBag ()
Observable <Int >.empty()
.subscribe { event in
print (event)
}.disposed(by: disposeBag)
复制代码
just
just是创建一个sequence只能发出一种特定的事件,能正常结束
let disposeBag = DisposeBag ()
Observable .just("coderwhy" )
.subscribe { event in
print (event)
}.disposed(by: disposeBag)
复制代码
of
of是创建一个sequence能发出很多种事件信号
let disposeBag = DisposeBag ()
Observable .of("a" , "b" , "c" )
.subscribe(onNext: { element in
print (element)
})
.disposed(by: disposeBag)
复制代码
from
let disposeBag = DisposeBag ()
Observable .from(["a" , "b" , "c" ])
.subscribe(onNext: { print ($0 ) })
.addDisposableTo(disposeBag)
复制代码
create
我们也可以自定义可观察的sequence,那就是使用create
create操作符传入一个观察者observer,然后调用observer的onNext,onCompleted和onError方法。返回一个可观察的obserable序列。
fileprivate func createObservable() -> Observable<Any>{
return Observable.create({ (observer: AnyObserver<Any>) -> Disposable in
observer.onNext("123" )
observer.onNext("abc" )
observer.onCompleted()
return Disposables.create()
})
}
复制代码
let ob = self.createObservable()
ob.subscribe ({ (event: Event<Any>) in
print (event)
}).disposed(by: bag)
复制代码
range
range就是创建一个sequence,他会发出这个范围中的从开始到结束的所有事件
Observable .range(start: 1 , count : 10 )
.subscribe { (event : Event <Int >) in
print (event)
}.disposed(by: bag)
复制代码
repeatElement
Observable .repeatElement("hello world" )
.take(3 )
.subscribe(onNext: { print ($0 ) })
.disposed(by: bag)
复制代码