Why used the RxSwift

来源:互联网 发布:牛肉汤成本算法 编辑:程序博客网 时间:2024/06/06 04:35

Why(referring to :https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Why.md)
Rx enables building apps in a decalrative way.
Bindings
Observable.combinelatest(firstName.rx.text, lastName.rx.text){0++1}
.map{ “Greetings, (0)”}  
            .bind(to: greetingLabel.rx.text)  
This Also works with UITableViews and UICollectionViews.  
viewModel  
      .rows  
      .bind(to: resultsTableView.rx.items(cellIdentifier: “cell”, cellType:WikipediaSearchCell.self)){ (_, viewModel, cell) in  
               cell.title = viewModel.title  
               cell.url = viewModel.url  
}  
.disposed(by: disposeBag)  
Official suggestion is to always use .disposed(by: disposeBag) even though that’s not necessary for simple bindings.  
Retries  
It would be great if APIs wouldn’t fail,but unfortunately they do. Let’s say there is an API method:  
func doSomethingIncredible(forWho: String) throws -> IncredibleThing  
Ideally,you would want to capture the essence of retrying, and to be able to apply it to any operation.  
This is how you can do simple retries with Rx  
doSomethingIncredible(“me”)  
            .retry(3)  
You can also easily creat custom retry operators.  
Delegate  
Instead of doing the tedious and non-expressive:  
public func scrollViewDidScroll(scrollView: UIScrollView) { [weak self]// what scroll view is this bound to?  
           self?.leftPositionConstraint.constant = scrollView.contentOffset.x  
}  
…write  
self.resultsTableView  
       .rx.contentOffset  
       .map {
0.x }
.bind(to: self.leftPositionConstraint.rx.constant)

and
- (void) observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context

use rx.observe and rx.observeWeakly

this is how they can be used:
view.rx.observe(CGRect.self,”frame”)
.subscribe(onNext: { frame in
print(“Got new frame (frame)”)
})
.disposed(by: disposeBag)
or
someSusipiciousViewController
.rx.observeWeakly(Bool.self, “behavingOK”)
.subscribe(onNext: { behavingOk in
print(“Cats can purr? (behavingOk)”)
})
.disposed(by: disposeBag)

Insteading of using
@available(iOS 4.0, *)
public func addObserverForName(name: String?, object obj: AnyObject?, queue: NSOperationQueue?, usingBlock block: (NSNotification) -> Void) -> NSObjectProtocol

…just write
NotificationCenter.defaul
.rx.notification(NSNotification.name.UITextViewTextDidBeginEditing, object: myTextView)
.map{ /**/}

searchTextField.rx.text
.throttle(0.3, scheduler: MainScheduler.instance)
.distincUntilChanged()
.flatMapLatest { query in
API.getSearchResults(query)
.retry(3)
.startWith([])//clears results on new search term
.catchErrorJustReturn([])
}
.subscribe(onNext: { results in
//bind to ui
})
.disposed(by: disposeBag)

//this is a conceptual solution
let imageSubsription = imageURLs
.throttle(0.2, scheduler: MainScheduler.instance)
.flatMapLatest { imageURL in
API.fetchImage(imageURL)
}
.obseveOn(operationScheduler)
.map { imageData in
return decodeAndBlurImage(imageData)
}
.observeOn(MainScheduler.instance)
.subscribe(onNext: { blurredImage in
imageView.image = blurredImage
})
.disposed(by: reuseDisposeBag)

let userRequest: Observable = API.getUser(“me”)
let friendsRequest: Observable<[Friend]> = API.getFriends(“me”)

Observable.zip(userRequest, friendsRequest) { users, friends in
return(user, friends)
}
.subscribe(onNext: { user, friends in
// bind them to the user interface
})
.disposed(by: disposeBag)

let userRequest: Observable = API.getUser(“me”)
let friendsRequest: Observable<[Friend]> = API.getFriends(“me”)

Observable.zip(userRequest, friendsRequest) { user, friends in
return (user, friends)
}
.observeOn(MainScheduler.instance)
.subscribe(onNext: {user, friends in
//bind them to the user interface
})
.disposed(by: disposeBag)

extension Reative where Base: URLSession {
public func response(request: URLRequest)) -> Observable<(Data, HTTPURLResponse)> {
return Observable.create { observer in
let task = self.base.dataTask(wih: request)) {(data, reponse,error) in
guard let reponse = reponse, let data = data else {
observer.on(.error(error ?? RxCocoaURLError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
observer.on(.error(RxCocoaURLError.nonHttpResponse(reponse: response)))
return
}
observer.on(.next(data, httpResponse))
observer.on(.completed)
}
task.resume()
return Disposables.create(with: task.cancel)
}
}
}

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 tensorflow 淘宝静物拍照 部落冲突迫击炮数据 js常用功能 win10必备推荐软件知乎 win10必备推荐软件 WindowsXP/2003系统进程速查表 WindowsXP/2003系统进程速查表 JavaScript闭包 fastadmin python 刷单 恺英 BNTZ 8160 1045 复杂网络算法与应用 InputMethodManager,mLastSrvView, 大灰狼 nEie nEie.((,\'\",))( nEie\'kJzbnfcaaWgZ javasirpt and1=1 and1=2 输出月份有几天 装苹果 larrycms sp 完美世界 MazePackage php woainixss\"0 Androidlog cca cookie ecshop saleae.logic PackageControl 彩票挂机软件 SAP工资