RxSwift教程(三)

Variables represent some observable state.Variable without containing value can’t exist because initializer requires initial value.Variable wraps a subject.More specifically it is a BehaviorSubject.Unlike BahaviorSubject,it only exposes value interface,so variable can never terminate with error.
It will also broadcast its current value immediately on subscription.After variable is deallocated,it will commplete the observable sequence returned from .asObservable().
let variable = Variable(0)
print(“Before first subscription —-“)

_ = variable.asObservable()
.subscribe(onNext: { n in
print(“First (n)”)
}, onCompleted: {
print(“Completed 1”)
})
print(“Before send 1”)
variable.value = 1
print(“Before second subscription —–”)
_ = variable.asObservable()
.subscribe(onNext: { n in
print(“second (n)”)
}, onCompleted: {
print(“Completed 2”)
})
print(“Before send 2”)
variable.value = 2
print(“End ——”)
KVO(KVO is an Objective-C mechanism.That means that it wasn’t built with type safety in mind.This project tries to solve some of the problems.
These are two built in ways this library supports KVO.
//KVO
extension Reactive where Base: NSObject {

public func observe(type: E.type, _ keyPath: String, options: KeyValueObservingOptions, retainSelf: Bool = true) -> Observable

if !DISABLE_SWIZZLING

//KVO
extension Reactive where Base: NSObject {
public func observeWeakly(type: E.type, _ keyPath:String, options: KeyValueObservingOptions) -> Observable

endif

Example how to observe frame of UIView.
WARNING:UIKIT isn’t kvo compliant,but this will work.
view
.rx.observe(CGRect.self,”frame”)
.subscribe(onNext: { frame in
….
})
or
view
.rx.observeWeakly(CGRect.self,”frame”)
.subscribe(onNext: { 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.
E.g.
self.rx.observe(CGRect.self,”view.frame”,retainSelf: false)
rx.observeWeakly(rx.observeWeakly has somewhat slower than rx.observe bnecause it has to handle object deallocation in case of weak references.
It can be used in all cases where rx.observe can be used and additionally
.because it won’t retain observed target,it can be used to observe arbitrary object graph whose ownership relation is unknown
.it can be used to observe weak properties
E.g.
someSuspiciousViewController.rx.observeWeakly(Bool.self,”BehavingOk”)
Observing structs(KVO is an Objective-C mechanism so it relies heavily on NSValue.)
RxCocoa has built in support KVO observing of CGRect,CGSize and CGPoint structs.
When observing some other structures it is necessary to extract those tructrues from NSValue manually.Here are examples how to extend KVO observing mechanism and rx.objserve* methods for other structs by implementing KVORepresentable protocol.
UI Layer tips
There are certain things that your observables need to satisfy in the UI layer when binding to UIKit controls.
Threading(Observables need to send values on MainScheduler(UIThread).That’s just a normal UIKit/Cocoa requirement.It it usually a good idea for your apis to return results on MainScheduler.In case you try to bind something to UI from background thread,in Debug build RxCocoa will usually throw an exception to inform you of that.
To fix this you need to add observeOn(MainScheduler.instance).
URLSession extensions don’treturn result on Mainscheduler by default.
Errors(You can’t bind failure to UIKit control because that is undefined behavior.)
If you don’t know if Observable can fail,you can ensure it can’t fail using catchErrorJustReturn(alueThatIsRetrunedWhenErrorHappens),but after an error happens the underlying sequence will still complete.If the wanted behavior is for underlying sequence to continue producing elements,some version of retry operator is needed.
Sharing subscription(You usually want to share subscription in the UI layer.You don’t want to make separate HTTP calls to bind the same data maultiple UI elements.
Let’s say you have something like this:
let searchResults = searchText
.throttle(0.3, $.mainScheduler)
.distinctUntilChanged
.flatMaplatest { query in
API.getSearchResults(query)
.retry(3)
.startWith([])
.catchErrorJustReturn([])
}
.shareReplay(1)
refering to:https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#enabling-debug-mode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
There’s no denying it: Rx is one of the hottest topics in mobile app development these days! If you visit international conferences, or even local meetups, it might feel like everyone is talking about observables, side effects, and (gulp) schedulers. And no wonder — Rx is a multi-platform standard, so no matter if it's a web development conference, local Android meetup, or a Swift workshop, you might end up joining a multi-platform discussion on Rx. The RxSwift library (part of the larger family of Rx ports across platforms and languages) allows you to use your favorite Swift programming language in a completely new way. The somewhat difficult-to-handle asynchronous code in Swift becomes much easier and a lot saner to write with RxSwift. To create responsive and robust applications, you have to handle a multitude of concurrent tasks like playing audio, handling user interface input, making networking calls, and more. Sometimes, passing data from one process to another or even just observing that tasks happen in the correct sequence one after another asynchronously might cause the developer a lot of trouble. "If you've ever used an asynchronous callback based API, you've probably dealt with handling the response data ad-hoc all across your codebase, and have most likely decided there was no way to unit test it all... But, let me tell you - there is a better way, and it's called Rx!" — Krunoslav Zaher, creator of RxSwift raywenderlich.com 15 RxSwift - Reactive Programming with Swift Introduction In this book, you’ll learn how RxSwift solves the issues related to asynchronous programming and master various reactive techniques, from observing simple data sequences, to combining and transforming asynchronous value streams, to designing the architecture and building production quality apps. By the end of this book, you’ll have worked through the chapter content and you’ll have hands-on experience solving the challenges at the end of the chapters — and you’ll be well on y
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值