variables
Variable 其實(shí)就是一個(gè)behaviorSubject
, 改Variable 僅僅暴漏了一個(gè)value
接口乓序,因此variable 不能手動(dòng)調(diào)用終止或失敗
只要subscribe 他就會(huì)立刻廣播他當(dāng)前的值
func testVariable(){
let variable = Variable(0)
print("before first subscription.....")
let v = variable.asObservable().subscribe(onNext: { (vint) -> Void in
print("first ->\(vint)")
}, onError: { (error) -> Void in
print("error")
}, onCompleted: { () -> Void in
print("completed first .....")
}) { () -> Void in
}
print("before send 1 ")
variable.value = 1;
print("Before second subscription.....")
variable.asObservable().subscribe(onNext: { (value ) -> Void in
print("second->\(value)")
}, onError: { (error) -> Void in
print("error Second")
}, onCompleted: { () -> Void in
print("second completed")
}) { () -> Void in
}
variable.value = 2;
print("end .....")
}
輸出如下:
before first subscription.....
first ->0
before send 1
first ->1
Before second subscription.....
second->1// 這個(gè)是第一個(gè)的值
first ->2
second->2
end .....
completed first .....
second completed
KVO
view.rx_observe(CGRect.self,"frame").subscribeNext{
frame in
....
}
or
view .rx_observeWeakly(CGRect.self, "frame") .subscribeNext { frame in ... }
rx_observe
is more performant because it’s just a simple wrapper around KVO mechanism, but it has more limited usage scenarios
it can be used to observe paths starting from self
or from ancestors in ownership graph (retainSelf = false
)
it can be used to observe paths starting from descendants in ownership graph (retainSelf = true
)
the paths have to consist only of strong
properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
- rx_observeWeakly
運(yùn)行效率肯能比rx_observe 慢侍匙,因?yàn)樗枰雎穡eak reference 的釋放。
除了rx_observe 能做的以外犁钟,rx_observeWeakly還能
- 可以觀察任何擁有關(guān)系未知的對(duì)象影锈,因?yàn)樗粫?huì)retain 該target
- 可以觀察
weak
屬性
someSuspiciousViewController.rx_observeWeakly(Bool.self, "behavingOk")
Threading
Observable
需要在MainScheduler
(UIThread)中發(fā)送values
observeOn(MainScheduler.instance)