本文介紹了函數響應式編程(FRP)以及 RxSwift 的一些內容, 源自公司內部的一次分享.html
一般,一個函數儘可能不要修改外部的一些變量。 函數的返回值有惟一性。react
- (MTFilterInfoModel *)filterInfoByFilterID:(NSInteger)filterID
ofTheme:(NSString *)themeNumber {
if (themeNumber) {
NSArray <MTFilterInfoModel *> *filterModels = [self filterInfosByThemeNumber:themeNumber];
for (MTFilterInfoModel *filter in filterModels) {
if (filter.filterID == filterID) {
return filter;
}
}
}
return nil;
}
複製代碼
vsios
let filters: [MTFilterInfoModel] = filterModels.filter { filter in
return filter.filterID == filterID
}
複製代碼
Array的filter函數能夠接收一個閉包Closure類型的參數。git
對數組中的每一個元素都執行一遍該Closure,根據Closure的返回值決定是否將該元素做爲符合條件的元素放入查找結果(也是一個Array)中。github
Objective-C中可使用enumerateObjectsUsingBlock。編程
*** 注重Action VS 注重Result ***json
func myFilter(filter: MTFilterInfoModel) -> Bool {
return filter.filterID == "5008"
}
let filters: [MTFilterInfoModel] = filterModels.filter(myFilter)
複製代碼
OC中的 blocks 或 enumeratexxx 也能夠作到。swift
Swift的高階函數使得其比Objective-C更適於函數式編程。api
就是把一個函數的多個參數分解成多個函數,而後把函數多層封裝起來,每層函數都返回一個函數去接收下一個參數。數組
即:用函數生成另外一個函數
「Swift 裏能夠將方法進行柯里化 (Currying),也就是把接受多個參數的方法變換成接受第一個參數的方法,而且返回接受餘下的參數而且返回結果的新方法。」
// currying
func greaterThan(_ comparer: Int) -> (Int) -> Bool {
return { $0 > comparer }
}
let isGreaterThan10 = greaterThan(10);
print(isGreaterThan10(2))
print(isGreaterThan10(20))
複製代碼
函數式Swift - 王巍
Masonry的寫法:
如B+中的StillCameraViewController:
[circleLoadingView mas_makeConstraints:^ (MASConstraintMaker *maker) {
maker.leading.equalTo(thumbBottom).with.offset(30);
maker.top.equalTo(thumbBottom);
maker.width.equalTo(thumbBottom);
maker.height.equalTo(thumbBottom);
}];
複製代碼
原理:
- (MASConstraint * (^)(id))equalTo {
return ^id(id attribute) {
return self.equalToWithRelation(attribute, NSLayoutRelationEqual);
};
}
- (MASConstraint * (^)(CGFloat))offset {
return ^id(CGFloat offset){
self.offset = offset;
return self;
};
}
複製代碼
本身實現一個:
@implementation Person
- (Person * (^)(NSString *))named {
return ^id(NSString *name) {
self.name = name;
return self;
};
}
- (Person * (^)(NSInteger))withAge {
return ^id(NSInteger age) {
self.age = age;
return self;
};
}
- (Person * (^)(NSString *))liveIn {
return ^id(NSString *city) {
self.city = city;
return self;
};
}
@end
複製代碼
使用以下:
Person *p = [[Person alloc] init];
[p.named(@"MyName").withAge(18).liveIn(@"Xiamen") doSomething];
複製代碼
登陸API -> 判斷token值 -> 請求API獲取真實的JSON數據 -> 解析獲得圖片URL -> 請求圖片 -> 填充UIImageView
[self request:api_login success:^{
if (isTokenCorrect) {
[self request:api_json success:^(NSData *data) {
NSDictionary *json = [self parse:data];
NSString *imgURL = json[@"thumbnail"];
[SDWebImageHelper requestImg:imgURL success:^(UIImage *image, NSError *error) {
runInMainQueue {
self.imageView.image = image;
}
}];
}];
}
}];
複製代碼
異步代碼,線程切換。
可使用相似 Promise 的方式解決異步代碼問題。
以上是Objective-C中的幾種狀態更新方式。
Reactive programming is programming with asynchronous data streams.
響應式編程與以上的幾種狀態更新方式不一樣,關鍵在於 *** 將異步可觀察序列對象模型化 *** 。
命令式編碼-Pull,響應式編程-Push。
Push的內容即爲異步數據流。
而函數式編程能夠很是方便地對數據流進行合併、建立、過濾、加工等操做,所以與響應式編程結合比較合適。
*** Function programming + Reactive programming + Swift -> RxSwift ***
btnClose.rx.tap
複製代碼
本身構造一個相似的
struct MT<Base> {
let base: Base
init(_ base: Base) {
self.base = base
}
}
protocol MTProtocol {
associatedtype CompatibleType
var mt: MT<CompatibleType> { get set }
}
extension MTProtocol {
var mt: MT<Self> {
get {
return MT(self)
}
set {
}
}
}
extension NSObject: MTProtocol {}
extension MT where Base: UIViewController {
var size: CGSize {
get {
return base.view.frame.size
}
}
}
複製代碼
使用以下:
print(viewController.mt.size)
複製代碼
這裏引用limboy博客中的一張圖:
number1與number2爲兩個UITextField
// 將兩個Observable綁定在一塊兒,構成一個Observable
Observable.combineLatest(number1.rx.text, number2.rx.text) { (num1, num2) -> Int in
if let num1 = num1, num1 != "", let num2 = num2, num2 != "" {
return Int(num1)! + Int(num2)!
} else {
return 0
}
}
// Observable發送的消息爲Int,不能與result.rx.text綁定,因此需使用map進行映射
.map { $0.description }
// Obsever爲result.rx.text
.bindTo(result.rx.text)
.addDisposableTo(CS_DisposeBag)
複製代碼
// 聲明Observable,可觀察對象
// username的text沒有太多參考意義,所以使用map來加工,獲得是否可用的消息
let userValidation = textFieldUsername.rx.text.orEmpty
// map的參數是一個closure,接收element
.map { (user) -> Bool in
let length = user.characters.count
return length >= minUsernameLength && length <= maxUsernameLength
}
.shareReplay(1)
let passwdValidataion = textFieldPasswd.rx.text.orEmpty
.map{ (passwd) -> Bool in
let length = passwd.characters.count
return length >= minUsernameLength && length <= maxUsernameLength
}
.shareReplay(1)
// 聲明Observable
// 組合兩個Observable
let loginValidation = Observable.combineLatest(userValidation, passwdValidataion) {
$0 && $1
}
.shareReplay(1)
// bind,即將Observable與Observer綁定,最終也會調用subscribe
// 此處是將isEnabled視爲一個Observer,接收userValidation的消息,作出響應
// 因此Observable發送的消息與Observer能接收的消息要對應起來(此處是Bool)
userValidation
.bindTo(textFieldPasswd.rx.isEnabled)
.addDisposableTo(CS_DisposeBag)
userValidation
.bindTo(lbUsernameInfo.rx.isHidden)
.addDisposableTo(CS_DisposeBag)
passwdValidataion
.bindTo(lbPasswdInfo.rx.isHidden)
.addDisposableTo(CS_DisposeBag)
loginValidation
.bindTo(btnLogin.rx.isEnabled)
.addDisposableTo(CS_DisposeBag)
複製代碼
監控UIScrollView的scroll操做。
一般:UIScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
// scrollView 1:
//
// scrollView 2:
//
// scrollView 3:
//
}
複製代碼
經過RxSwift:
根本:scrollView的contentOffset在變化
tableView.rx.contentOffset
.map { $0.y }
.subscribe(onNext: { (contentOffset) in
if contentOffset >= -UIApplication.shared.statusBarFrame.height / 2 {
UIApplication.shared.statusBarStyle = .lightContent
} else {
UIApplication.shared.statusBarStyle = .default
}
})
.addDisposableTo(CS_DisposeBag)
複製代碼
對於UITextField, UISearchController,UIButton等等,常見的使用步驟以下:
而使用RxSwift,則能夠作到 *** 高聚合,低耦合 ***
btnClose.rx.tap
.subscribe(onNext: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dismiss(animated: true, completion: nil)
})
.addDisposableTo(CS_DisposeBag)
複製代碼
可觀察對象,可組合。(發射數據)
next新的事件數據,complete事件序列的結束,error異常致使結束
因此next能夠屢次調用,而complete只有最後一次。
/// Type that can be converted to observable sequence (`Observer<E>`).
public protocol ObservableConvertibleType {
/// Type of elements in sequence.
associatedtype E
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
func asObservable() -> Observable<E>
}
複製代碼
此外,還有 *** create,just,of,from *** 等一系列函數
from: Converts an array to an observable sequence.
對Observable發射的數據或數據序列作出響應,作出特定的操做。
/// Supports push-style iteration over an observable sequence.
public protocol ObserverType {
/// The type of elements in sequence that observer can observe.
associatedtype E
/// Notify observer about sequence event.
///
/// - parameter event: Event that occured.
func on(_ event: Event<E>)
}
複製代碼
訂閱事件。
對事件序列中的事件,如next,complete,error進行響應,
extension ObservableType {
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription).
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
xxx
}
}
複製代碼
因此:
*** Rx的關鍵在於Observer訂閱Observable,Observable將數據push給Observer,Observer本身作出對應的響應。 ***
進行數據映射
extension ObservableType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (Self.E) throws -> R) -> RxSwift.Observable<R>
複製代碼
extension ObservableType {
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
public func bindTo(_ variable: RxSwift.Variable<Self.E>) -> Disposable
}
複製代碼
定義了釋放資源的統一行爲。
DisposeBag: 訂閱會有Disposable,自動銷燬相關的訂閱。可簡單相似autorelease機制
建立一個可添加新元素的Observable,讓訂閱對象可以接收包含初始值與新值的事件。
BahaviorSubject表明了一個隨時間推移而更新的值,包含初始值。
let s = BehaviorSubject(value: "hello")
// s.onNext("hello again") // 會替換到hello消息
s.subscribe { // 不區分訂閱事件,因此打印 next(hello)
print($0)
}
// s.subscribe(onNext: { // 僅區分訂閱事件,因此打印next事件接收的數據 hello
// print($0)
// })
.addDisposableTo(CS_DisposeBag)
s.onNext("world") // 發送下一個事件
s.onNext("!")
s.onCompleted()
s.onNext("??") // completed以後即不能響應了
複製代碼
PublishSubject與BehaviorSubject相似,
但PublishSubject不須要初始值,且不會將最後一個值發送給Observer。
struct Person {
let name = PublishSubject<String>()
let age = PublishSubject<Int>()
}
let person = Person()
person.name.onNext("none")
person.age.onNext(0)
Observable.combineLatest(person.name, person.age) {
"\($0) \($1)"
}
.debug()
.subscribe {
print($0)
}
.addDisposableTo(CS_DisposeBag)
person.name.onNext("none again") // 該none again數據不會發送
person.name.onNext("chris")
person.age.onNext(18)
person.name.onNext("ada")
複製代碼
使用了combineLatest,則會等待須要combine的數據都準備好了纔會發送。
能夠經過combineLatest來直觀感覺。
使用PublishSubject的log以下:
2017-06-22 16:46:51.160: AppDelegate.swift:186 (basicRx()) -> subscribed
2017-06-22 16:46:51.161: AppDelegate.swift:186 (basicRx()) -> Event next(chris 18)
next(chris 18)
2017-06-22 16:46:51.162: AppDelegate.swift:186 (basicRx()) -> Event next(ada 18)
next(ada 18)
2017-06-22 16:46:51.162: AppDelegate.swift:165 (basicRx()) -> Event completed
completed
2017-06-22 16:46:51.162: AppDelegate.swift:165 (basicRx()) -> isDisposed
複製代碼
能夠經過combineLatest來直觀感覺。
除了combine,還可使用concat,merge,zip等到操做。
zip須要兩個元素都有新值纔會發送數據。
let personZip = Person()
// zip須要兩個元素都有新值纔會發送
Observable.zip(personZip.name, personZip.age) {
"\($0) \($1)"
}
.subscribe {
print($0)
}
.addDisposableTo(CS_DisposeBag)
personZip.name.onNext("zip none") // 不會單獨發送
personZip.name.onNext("zip chris")// 放入序列中,等待age
personZip.age.onNext(18) // 結合zip none一塊兒發送
personZip.name.onNext("zip ada") // 永遠不會發送,在其以前已經有zip chris
personZip.age.onNext(20) // 結合zip chris一塊兒發送
personZip.name.onCompleted()
personZip.age.onCompleted()
複製代碼
打印的log以下:
next(zip none 18)
next(zip chris 20)
completed
2017-06-23 13:50:48.234: AppDelegate.swift:172 (basicRx()) -> Event completed
completed
2017-06-23 13:50:48.235: AppDelegate.swift:172 (basicRx()) -> isDisposed
複製代碼
zip的場景要好好體會下,爲什麼會是這兩個輸出。
能夠經過zip來直觀感覺。
Variable基於BahaviorSubject封裝的類,經過asObservable()保留出其內部的BahaviorSubject的可觀察序列。
表示一個可監聽的數據結構,能夠監聽數據變化,或者將其餘值綁定到變量。
Variable不會發生任何錯誤事件,即將被銷燬處理的時候,會自動發送一個completed事件。所以有些使用Variable
let v = Variable<String>("hello")
v.asObservable()
.debug()
.distinctUntilChanged() // 消除連續重複的數據
.subscribe {
print($0)
}
.addDisposableTo(CS_DisposeBag)
v.value = "world"
v.value = "world" // 不會對重複的"world"作出響應
v.value = "!"
複製代碼
打印log以下,能夠看出其發送的可觀察序列:
2017-06-22 16:22:57.208: AppDelegate.swift:162 (basicRx()) -> subscribed
2017-06-22 16:22:57.211: AppDelegate.swift:162 (basicRx()) -> Event next(hello)
next(hello)
2017-06-22 16:22:57.212: AppDelegate.swift:162 (basicRx()) -> Event next(world)
next(world)
2017-06-22 16:22:57.212: AppDelegate.swift:162 (basicRx()) -> Event next(world)
2017-06-22 16:22:57.212: AppDelegate.swift:162 (basicRx()) -> Event next(!)
next(!)
2017-06-22 16:22:57.212: AppDelegate.swift:162 (basicRx()) -> Event completed
completed
2017-06-22 16:22:57.212: AppDelegate.swift:162 (basicRx()) -> isDisposed
複製代碼
如 *** Subject, BehaviorSubject, Driver 等等 ***
RxSwift學習之旅 - Observable 和 Driver
*** RxSwift 與 RxCocoa ***
兩個Observable進行combine操做:
let loginValidation = Observable.combineLatest(userValidation, passwdValidataion) {
$0 && $1
}
.shareReplay(1)
複製代碼
對UITableView, UICollectionView的dataSource進行Rx的封裝。
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>()
複製代碼
dataSource.configureCell = xxx
複製代碼
準備一個Observable<[SectionModel<String, User>]>,而後與tableView進行相關bind便可
userViewModel.getUsers()
.bindTo(tableView.rx.items(dataSource: dataSource))
.addDisposableTo(CS_DisposeBag)
複製代碼
tableView.rx
.modelSelected(User.self)
.subscribe(onNext: { user in
print(user)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
self.present(loginVC, animated: true, completion: nil)
})
.addDisposableTo(CS_DisposeBag)
複製代碼
使用RxSwift來構建UICollectionView的步驟相似。
ViewModel以下:
struct Repo {
let name: String
let url: String
}
class SearchBarViewModel {
let searchText = Variable<String>("")
let CS_DisposeBag = DisposeBag()
lazy var repos: Driver<[Repo]> = {
return self.searchText.asObservable()
.throttle(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.flatMapLatest { (user) -> Observable<[Repo]> in
if user.isEmpty {
return Observable.just([])
}
return self.searchRepos(user: user)
}
.asDriver(onErrorJustReturn: [])
}()
func searchRepos(user: String) -> Observable<[Repo]> {
guard let url = URL(string: "https://api.github.com/users/\(user)/repos") else {
return Observable.just([])
}
return URLSession.shared.rx.json(url: url)
.retry(3)
.debug()
.map {
var repos = [Repo]()
if let items = $0 as? [[String: Any]] {
items.forEach {
guard let name = $0["name"] as? String,
let url = $0["url"] as? String
else { return }
repos.append(Repo(name: name, url: url))
}
}
return repos
}
}
}
複製代碼
ViewController中的代碼以下:
var searchBarViewModel = SearchBarViewModel()
tableView.tableHeaderView = searchVC.searchBar
searchBar.rx.text.orEmpty
.bindTo(searchBarViewModel.searchText)
.addDisposableTo(CS_DisposeBag)
searchBarViewModel.repos
.drive(tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, repo, cell) in
cell.textLabel?.text = repo.name
cell.detailTextLabel?.text = repo.url
}
.addDisposableTo(CS_DisposeBag)
複製代碼
UISearchBar中的text與ViewModel中的searchText進行綁定,
而ViewModel中的searchText是Variable類型,做爲Observable會在MainScheduler中輸入間隔達到0.3s只後會觸發調用searchRepos函數進行搜索。
repos做爲Driver,其中元素是包含Repo的數組。Driver一樣封裝了可觀察序列,但Driver只在主線程執行。
因此,作數據綁定可使用bindTo和Driver,涉及到UI的綁定能夠儘可能使用Driver。
在本例中,跟repos綁定的便是tableView.rx.items,即repos直接決定了tableView中的items展現內容。
對應使用URLSession進行網絡請求的場景,RxSwift也提供了很是方便的使用方式。注意各個地方Observable的類型保持一致便可。
另外,注意 *** throttle *** , *** flatMapLatest *** 及 *** distinctUntilChanged *** 的用法。
數據綁定,精簡Controller,便於單元測試。
數據綁定額外消耗,調試困難,
*** 注意input與output便可 ***
*** 難點在於如何合理的處理ViewModel與View的數據綁定問題。***
此處關於寫好ViewModel的建議,出自:
struct UserViewModel {
let userName: String
let userAge: Int
let userCity: String
}
textFieldUserName.rx.text.orEmpty
.bindTo(userViewModel.userName)
// 不推薦
textFiledUserAge.rx.text.orEmpty
.map { Int($0) }
.bindTo(userViewModel.userAge)
複製代碼
userViewModel.register()
self.btnRegister.rx.tap
.bindTo(userViewModel.register)
複製代碼
如
struct UserViewModel {
let user: UserModel
}
struct UserViewModel {
let userName: String
let userAge: String
let userCity: String
}
複製代碼
RxSwift Reactive Programming with Swift by raywenderlich.com