一单刁、前言
最近正在學(xué)習(xí)iOS底層框架灸异,在學(xué)習(xí)RxSwift的課程時,涉及到了函數(shù)響應(yīng)式編程的思想,這讓我想起了在工作項目中使用到的ReactiveCocoa第三方庫绎狭,它里面也使用了函數(shù)響應(yīng)式編程思想细溅,之前只是看了簡單的介紹,并會使用它而已儡嘶,現(xiàn)在必須徹底去掌握該思想--函數(shù)響應(yīng)式編程(FRP(Functional Reactive Programming)),下面就讓我們一起揭開函數(shù)響應(yīng)式編程思想的神秘面紗喇聊。
二、基本概念
在iOS開發(fā)中蹦狂,有三種編程思想誓篱,分別是鏈?zhǔn)骄幊獭⒑瘮?shù)式編程和響應(yīng)式編程凯楔。
1窜骄、鏈?zhǔn)骄幊?/h2>
- 定義:它是可以通過“點”語法,進(jìn)行調(diào)用所執(zhí)行的函數(shù)或代碼塊摆屯,并可以連續(xù)的使用邻遏。
- 特點:方法必須有返回值,并且該值是對象本身虐骑;返回值的形式可以是Block塊(返回值必須是對象本身准验,也可帶參數(shù))也可以是對象本身。
- 舉例:
YLGPerson.h文件
- (YLGPerson *(^)(NSString *food))eat;
- (YLGPerson *(^)(NSString *time))run;
YLGPerson.h文件
- (YLGPerson *(^)(NSString *food))eat;
- (YLGPerson *(^)(NSString *time))run;
YLGPerson.m文件
//MARK: -- Eat
- (YLGPerson *(^)(NSString *food))eat {
return ^(NSString *food) {
NSLog(@"吃了%@",food);
return self;
}
}
//MARK: -- Run
- (YLGPerson *(^)(NSString *time))run {
return ^(NSString *time) {
NSLog(@"跑了%@分鐘",time);
return self;
}
}
ViewController.m文件
YLGPerson *person = YLGPerson.new;
person.eat(@"香蕉").run(@"60").eat(@"牛奶")
注:點語法使得代碼簡單易讀廷没,書寫方便糊饱。鏈?zhǔn)骄幊痰拇恚簃asonry框架
2、函數(shù)式編程
- 定義:對象調(diào)用函數(shù)后颠黎,此函數(shù)的返回值就是該對象本身另锋,進(jìn)而可以繼續(xù)調(diào)用該對象的其他函數(shù)。
- 特點:可以嵌套的調(diào)用對象所擁有的函數(shù)狭归。
- 舉例:
YLGPerson.h文件
@property (nonatomic, assign, readonly) NSInteger result;
- (YLGPerson *)calculator:(NSInteger (^)(NSInteger result))block;
YLGPerson.m文件
@property (nonatomic, assign, readwrite) NSInteger result;
- (YLGPerson *)calculator:(NSInteger (^)(NSInteger result))block {
_result = block(_result);
return self;
}
ViewController.m文件
YLGPerson *person = YLGPerson.new;
[person calculator:^NSInteger (NSInteger result){
result += 8;
result *=2;
return result;
}];
注:函數(shù)式編程的代表:ReactiveCocoa框架
3夭坪、響應(yīng)式編程
- 定義:某一個變量的值會隨著另一個變量的值改變而改變,它是和事件流有關(guān)的編程模式唉铜。
- 特點:在編程過程中建立一個動態(tài)的數(shù)據(jù)流關(guān)系台舱。
- 舉例:
a = 2;
b = 6;
c = a + b; //c is 8
b = 1;
//now what is the value of c?
如果使用FRP,c的值將會隨著b的值改變而改變潭流,所以叫做「響應(yīng)式編程」竞惋。比較直觀的例子就是Excel,當(dāng)改變某一個單元格的內(nèi)容時灰嫉,該單元格相關(guān)的計算結(jié)果也會隨之改變拆宛。
FRP提供了一種信號機(jī)制來實現(xiàn)這樣的效果,通過信號來記錄值的變化讼撒。信號可以被疊加浑厚、分割或合并股耽。通過對信號的組合,就不需要去監(jiān)聽某個值或事件钳幅。如下圖:
三物蝙、函數(shù)響應(yīng)式編程
-
定義:響應(yīng)式編程思想為體,函數(shù)式編程思想為用敢艰。如下圖:
函數(shù)響應(yīng)式編程.png - 優(yōu)點:簡潔明了诬乞,可讀性強(qiáng),復(fù)用性強(qiáng)钠导。
- 舉例
- 傳統(tǒng)寫法
var customButton: UIButton! = UIButton()
customButton.addTarget(self, action: #selector(clickCustomButton), for: .touchUpInside)
@objc func clickCustomButton() {
print("customButton clicked震嫉!")
}
- RxSwift寫法
self.customButton.rx.tap //事件序列
.subscribe(onNext: { () in //訂閱
print("RxSwift customButton clicked!")
}, onError: { (error) in //發(fā)生錯誤回調(diào)
print("錯誤信息")
}, onCompleted: { //任務(wù)完成回調(diào)
print("訂閱完成")
})
.disposed(by: DisposeBag()) //對象銷毀
參考文檔:
https://blog.csdn.net/kyl282889543/article/details/96981571#3__232
https://limboy.me/tech/2013/06/19/frp-reactivecocoa.html
http://www.reibang.com/p/df4a949e3966