接触Rx有种让你相见恨晚的感觉。
简书:https://www.jianshu.com/p/b66bfe4bdf7d
本文札记Observable
的使用方法
Observable.of()
Observable.from([])
需求如下:筛选以下数组,取偶数
"1","2","3","4","5","6","7"
Observable.from(["1","2","3","4","5","6","7"]).map({Int($0)}).filter({
if let item = $0, item % 2 == 0{
return true
}
return false
})
map
函数Sring转为整型
filter
筛选,规则为 item % 2 == 0
现在Observable没有被执行,因为没有Observer订阅,
对于观察者这一描述是有些僵硬的,在RxSwift中,执行事件这一行为被称为观察者,ps:这个名字感觉不舒服,每一个观察者都是由闭包构成的
然而:
cold observable --> 只有订阅才会执行
hot observable --> 自发执行
刚创建的是 cold observable
订阅代码:
let evenNumsObservable = Observable.from(["1","2","3","4","5","6","7"]).map({Int($0)}).filter({
if let item = $0, item % 2 == 0{
print(item)
return true
}
return false
})
//全程订阅
evenNumsObservable.subscribe { (event) in
print("event,\(event)")
}
//中途订阅
evenNumsObservable.skip(2).subscribe { (event) in
print("event,\(event)")
}
skip(2)
: 用来模拟中途订阅,订阅的事件为 “3”,”4”,”5”,”6”,”7”
subscribe
也是一个operator
,用于把事件的订阅者(observer
)和事件的产生者(observable
)关联起来
observabl
e(被观察者) 与observer
(观察者)有着如下约定:
当observable
正常发送事件的时候,会调用observer
提供的 onNext
方法,并把对应的事件传递给他(observe
r),
当observable
正常结束的时候, 会调用observe
r提供的 onCompleted
方法,这个调用不会传递任何参数,只是简单地通知obersver
所有事件已经结束
当observable
发生错误的时候, 会调用observer
提供的 onError
方法
如下:
Observable.interval(1, scheduler: MainScheduler.instance).subscribe(
onNext:{print("\($0)")},
onError:{print($0)},
onCompleted:{print("completed")},
onDisposed:{print("The queue was disposed")} )
当observable
使用的资源被回收的时候,会调用observer
提供的 onDisposed
方法
于是乎:
var bag = DisposeBag()
Observable.interval(1, scheduler: MainScheduler.instance).subscribe(
onNext:{print("\($0)")},
onDisposed:{print("The queue was disposed")} ).disposed(by: bag)
delay(5) {
bag = DisposeBag()
}
bag
销毁时,bag中绑定的资源也会被销毁
disposeable
理解为一个订阅对象 可以通过该对象取消订阅
理解起来如下:
override public func subscribe<O>(_ observer: O) -> Disposable where Element == O.E, O : ObserverType
let disposed = Observable.interval(1, scheduler: MainScheduler.instance).subscribe(
onNext:{print("\($0)")},
onDisposed:{print("The queue was disposed")} )
disposed.dispose()
比如:5s后结束
定义·一个·全局函数
public func delay(_ delay:Double,closure:@escaping ()->()){
DispatchQueue.main.asyncAfter(deadline: .now()+delay) {
closure()
}
}
执行如下:
delay(5) {
disposed.dispose()
}
在swift支持如下写法:
var bag = DisposeBag()//bag销毁时,bag中绑定的资源也会被销毁
Observable.interval(1, scheduler: MainScheduler.instance).subscribe(
onNext:{print("\($0)")},
onError:{print($0)},
onCompleted:{print("completed")},
onDisposed:{print("The queue was disposed")} ).disposed(by: bag)
delay(5) {
bag = DisposeBag()
}
let customOb = Observable.create({observer in
observer.onNext(10)
observer.onNext(11)
observer.onNext(12)
observer.onNext(14)
//发送错误
observer.onError(CustomNSError.somethingError)
//完成时调用completed
observer.onCompleted()
//返回值为 Disposable
return Disposables.create()
})
Observable
表示被观察的值为Int序列
特别注意:一旦发生错误,那么就不会调用完成,而是直接调用 return Disposable
自定义事件的订阅
let disposeBag = DisposeBag()
customOb.subscribe(
onNext:{print($0)},
onError:{print($0)},
onCompleted:{print("Completed")},
onDisposed:{print("Game over")}
).disposed(by: disposeBag)
log:
/*
10
11
12
14
somethingError
Game over
*/
在实际的编程中,有时会串联多个operator对事件进行处理,虽然这样写很方便,但是调试起来会很麻烦,紧密串联的代码然我们很难方便的洞察每一个环节的状态
customOb.do(
onNext:{print("do",$0)},
onError:{print("do",$0)},
onCompleted:{print("do","Completed")},
onDispose:{print("do","Game over")}
).subscribe(
onNext:{print($0)},
onError:{print($0)},
onCompleted:{print("Completed")},
onDisposed:{print("Game over")}
).disposed(by: disposeBag)
log:
//operator do 具有旁路特性 用法和subscribe非常相似,用来解决上述问题
/*
do 10
10
do 11
11
do 12
12
do 14
14
do somethingError
somethingError
Game over
do Game over
*/
一个专门用于调试的operator
customOb.debug().subscribe(
onNext:{print($0)},
onError:{print($0)},
onCompleted:{print("Completed")},
onDisposed:{print("Game over")}
).disposed(by: disposeBag)
log:
/*
2018-06-24 18:36:39.204: CreatOperatorLearn.swift:76 (viewDidLoad()) -> subscribed
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> Event next(10)
10
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> Event next(11)
11
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> Event next(12)
12
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> Event next(14)
14
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> Event error(somethingError)
somethingError
Game over
2018-06-24 18:36:39.206: CreatOperatorLearn.swift:76 (viewDidLoad()) -> isDisposed
*/