RxSwift(5) 练习

variables

Variable 其实就是一个behaviorSubject, 改Variable 仅仅暴漏了一个value 接口,因此variable 不能手动调用终止或失败
只要subscribe 他就会立刻广播他当前的值

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// 这个是第一个的值
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
    运行效率肯能比rx_observe 慢,因为他需要出路weak reference 的释放。
    除了rx_observe 能做的以外,rx_observeWeakly还能
  1. 可以观察任何拥有关系未知的对象,因为他不会retain 该target
  2. 可以观察weak属性
someSuspiciousViewController.rx_observeWeakly(Bool.self, "behavingOk")

Threading

Observable 需要在MainScheduler(UIThread)中发送values

observeOn(MainScheduler.instance)

shareReplay

你可能感兴趣的:(RxSwift(5) 练习)