//创建 Observable 序列 func createObservable(){ /* let observable = Observable<Int>.just(5) let observableStr = Observable.of("A","B","C") let observableArr = Observable.from(["A","B","C"]) let observableEmpty = Observable<Int>.empty() let observareNaver = Observable<Int>.never() let observareError = Observable<Int>.error(NSError.init()) let observareRange = Observable.range(start: 1, count: 5) let observareRange1 = Observable.of(1,2,3,4,5) let observareGen = Observable.generate(initialState: 0, condition: {$0 <= 10}, iterate: {$0 + 2}) print(observable,observableStr,observableArr,observableEmpty, observareError,observareNaver,observareRange,observareRange1,observareGen) */ let observareCreate = Observable<String>.create { (observer) -> Disposable in //观察者发出事件 observer.onNext("rxswift.com") //发出完成事件 observer.onCompleted() //因为一个订阅行为会有一个Disposable类型的返回值,所以在结尾一定要returen一个Disposable return Disposables.create() } observareCreate.subscribe { (str) in print(str) }.dispose() //工厂模式 var isOdd = true let factory:Observable<Int> = Observable.deferred { () -> Observable<Int> in isOdd = !isOdd if isOdd { return Observable.of(1,3,5,7) }else{ return Observable.of(2,4,6,8) } } factory.subscribe { (result) in print(result) }.dispose() factory.subscribe { (event) in print(event) }.dispose() //定时器唯一性 let obervableTime = Observable<Int>.timer(5, scheduler: MainScheduler.instance) print(obervableTime.subscribe { (event) in print(event) }) let observableStr = Observable.of("A","B","C") //使用subscription常量存储这个订阅方法 let subscription = observableStr.subscribe { (element) in print(element) } //销毁订阅 subscription.dispose() let disposeBag = DisposeBag.init() let obserable = Observable.of("A","B","C") obserable.subscribe { (event) in print(event) }.disposed(by: disposeBag) //每个一秒发出一个索引 map ---bind 进行绑定 let obserable1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) obserable1.map{"当前索引:($0)"}.bind { [weak self](text) in self?.label.text = text }.disposed(by: disposeBag) let obserable2:AnyObserver<String> = AnyObserver.init { (event) in switch event{ case .next(let data): print(data) case .error(let error): print(error) case .completed: print("Completable") } } obserable.subscribe(obserable2).dispose() let obserable3:AnyObserver<String> = AnyObserver.init { (event) in switch event { case .next(let text): self.label.text = text default: break } } let obserable4 = Observable<Int>.interval(1, scheduler: MainScheduler.instance) obserable4.map{"当前索引:($0)"}.bind(to: obserable3).disposed(by: disposeBag) //观察者模式 let observer3:Binder<String> = Binder.init(label) { (view, text) in //刷新UI view.text = text } let observable = Observable<Int>.interval(1, scheduler: MainScheduler.instance) observable.map{ "当前索引:($0)" }.bind(to: observer3) .disposed(by: disposeBag) let observableLbl = Observable<Int>.interval(1, scheduler: MainScheduler.instance) //RXSwift绑定属性 observableLbl.map {"当前索引:($0)"} .bind(to: label.rx.text) .disposed(by: disposeBag) }