近期開發(fā)RN項目對函數(shù)式編程有了一點點的理解汤踏,回過頭看native的函數(shù)式編程框架RAC,有點茅塞頓開的感覺舔腾,在此記錄下RAC源碼閱讀心得溪胶。
對于函數(shù)式編程,我個人感覺最大的好處就是代碼很緊湊稳诚,結(jié)構(gòu)簡潔而清晰哗脖。到oc語言里就是“block式”編程,舉個例子扳还,在處理輸入框的時候比如UITextField才避,使用UIKit原生的API需要遵循它的協(xié)議,實現(xiàn)代理方法監(jiān)聽輸入變化氨距;如果一個頁面有多個輸入框桑逝,甚至是一個輸入框的動態(tài)array,這個時候我們會想到如果回調(diào)是一個block俏让,在創(chuàng)建輸入框的時候就寫好了回調(diào)block肢娘,不僅代碼很集中,也不必做跨函數(shù)的事情區(qū)分回調(diào)來源舆驶。
引用sunnyReactive Cocoa Tutorial [0] = Overview中的一段比喻,原來的編程思想好比走迷宮而钞,走出迷宮需要在不同時間段記住不同狀態(tài)根據(jù)不同情況而做出一系列反應沙廉,繼而走出迷宮;RAC的思想好比是建迷宮臼节,在創(chuàng)建時就建立好聯(lián)系撬陵,一個事件來了會引發(fā)哪些響應鏈,都按照創(chuàng)建好的路線傳導网缝,像一個精密的儀器巨税,復雜但完整而自然。
最可見的變化就是代碼量大量減少粉臊,沒有多余的狀態(tài)變量草添,邏輯更清晰。
RACSignal
RAC是github開源的框架扼仲,有專門社區(qū)維護远寸,代碼的水平還是很高的抄淑。對我這種初學者說收貨很大。驰后。里面有很多關(guān)于宏肆资、block、runtime的高級用法灶芝,一些之前掌握不深的知識點都有新的理解郑原。
首先要看的肯定是RACSignal類了,對它的使用無非就是創(chuàng)建signal夜涕,訂閱(next犯犁、complete、error):
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe {
RACDynamicSignal *signal = [[self alloc] init];
//這里將didSubscribe block保存在信號里面钠乏,所以使用時要注意避免循環(huán)引用
signal->_didSubscribe = [didSubscribe copy];
return [signal setNameWithFormat:@"+createSignal:"];
}
創(chuàng)建就是將傳入的block保存起來栖秕,看這個block的名字也就知道,didSubscribe 即訂閱了信號才會執(zhí)行:
- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock {
NSCParameterAssert(nextBlock != NULL);
//創(chuàng)建一個subscriber
RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL];
return [self subscribe:o];
}
這里創(chuàng)建了一個RACSubscriber對象o晓避,并執(zhí)行了[self subscribe:o]簇捍。
RACSubscriber對象保存了next、error俏拱、completed三個block:
+ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed {
RACSubscriber *subscriber = [[self alloc] init];
subscriber->_next = [next copy];
subscriber->_error = [error copy];
subscriber->_completed = [completed copy];
return subscriber;
}
下一步執(zhí)行[self subscribe:o]并返回一個RACDisposable對象暑塑。這里稍微復雜一些,但從上面分析來看锅必,這一步要做的是執(zhí)行didSubscribe事格,并建立關(guān)聯(lián)在sendNext、sendError搞隐、sendCompleted時執(zhí)行訂閱者對應的block驹愚。
- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
NSCParameterAssert(subscriber != nil);
RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable];
subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable];
if (self.didSubscribe != NULL) {
RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{
RACDisposable *innerDisposable = self.didSubscribe(subscriber);
[disposable addDisposable:innerDisposable];
}];
[disposable addDisposable:schedulingDisposable];
}
return disposable;
}
好吧,一行一行看
已經(jīng)了解了RACSignal和RACSubscriber劣纲,還需要知道這個RACDisposable是干嘛的逢捺。
A disposable encapsulates the work necessary to tear down and cleanup a subscription.
disposable封裝了撤銷、清除一個訂閱所必須的一些工作癞季。
添加一個訂閱要支持可以隨時取消訂閱劫瞳,并在取消或完成時做好清理工作,看來disposable是干這些事情的绷柒。再回到[self subscribe:o]:
1.首先創(chuàng)建了一個RACCompoundDisposable志于,它是RACDisposable的一個子類,來看一段官方繞口令:
A disposable of disposables. When it is disposed, it disposes of all its contained disposables.
一個混合的disposable废睦,簡單講就是一個disposable的數(shù)組(內(nèi)部會有一些優(yōu)化伺绽,可以參照RACCompoundDisposable.m),當CompoundDisposable dispose時會dispose它包含的所有disposables。
2.創(chuàng)建一個subscriber憔恳,這一行看起來有點詭異:上一步創(chuàng)建了一個RACSubscriber對象o瓤荔,現(xiàn)在用o再創(chuàng)建一個RACPassthroughSubscriber賦給o,RACPassthroughSubscriber實現(xiàn)了RACSubscriber協(xié)議钥组,并且signal输硝、subcriber、disposable一應俱全程梦,看起來這個類會維系好三者之間的關(guān)系点把。實際上看并沒有什么管理三者關(guān)系的代碼存在,僅有一些DTrace的東西屿附,和Instruments有關(guān)郎逃。如果把這一行注掉,會發(fā)現(xiàn)并沒有什么影響挺份。
3.接下來就是關(guān)鍵的部分了褒翰,執(zhí)行didSubscribe block。這里用了一個subscriptionScheduler匀泊,是專門用來執(zhí)行subscription任務的优训,返回一個disposable是為了能夠在任務沒執(zhí)行前能控制取消掉它,也對應了disposable這個名字的含義各聘。scheduler內(nèi)部是gcd實現(xiàn)的揣非,disposable相當于一個外部的變量控制是否執(zhí)行這個任務:
- (RACDisposable *)schedule:(void (^)(void))block {
NSCParameterAssert(block != NULL);
RACDisposable *disposable = [[RACDisposable alloc] init];
dispatch_async(self.queue, ^{
if (disposable.disposed) return;
[self performAsCurrentScheduler:block];
});
return disposable;
}
這樣看下來,忽略一些實現(xiàn)細節(jié)躲因,其實這些類大概都是做了兩件事:1.把block存起來早敬;2.在合適的時機執(zhí)行它。
用一張圖簡單梳理下從創(chuàng)建signal大脉、訂閱和發(fā)布接收的關(guān)系:RAC源碼里其實有很多值得研究和學習的地方搞监,對宏、runtime镰矿、block的使用等腺逛。比如我們在寫RAC宏的時候
RAC(self.submitBtn, enabled) = RACObserve(self.submitBtnModel, enabled);
在寫完逗號敲property時會發(fā)現(xiàn)編譯器給出了正確的代碼提示,很神奇衡怀。具體可以看下這篇博客Reactive Cocoa Tutorial [1] = 神奇的Macros。
NSObject (RACSelectorSignal)
RAC相當于統(tǒng)一規(guī)范了異步事件的處理安疗。那么如何將一個異步事件的處理封裝成RACSignal的形式呢抛杨。
- 如果是block回調(diào)的API,相對比較簡單荐类,只需要創(chuàng)建signal并在回調(diào)block中sendNext怖现、sendComplete、sendError即可。
- 如果是target-action屈嗤,比如UIControl的事件潘拨,則只需要將target設置成相應的subscriber,比如UIControl (RACSignalSupport)分類中就只有這一個方法:
@implementation UIControl (RACSignalSupport)
- (RACSignal *)rac_signalForControlEvents:(UIControlEvents)controlEvents {
@weakify(self);
return [[RACSignal
createSignal:^(id<RACSubscriber> subscriber) {
@strongify(self);
[self addTarget:subscriber action:@selector(sendNext:) forControlEvents:controlEvents];
RACDisposable *disposable = [RACDisposable disposableWithBlock:^{
[subscriber sendCompleted];
}];
[self.rac_deallocDisposable addDisposable:disposable];
return [RACDisposable disposableWithBlock:^{
@strongify(self);
[self.rac_deallocDisposable removeDisposable:disposable];
[self removeTarget:subscriber action:@selector(sendNext:) forControlEvents:controlEvents];
}];
}]
setNameWithFormat:@"%@ -rac_signalForControlEvents: %lx", RACDescription(self), (unsigned long)controlEvents];
}
@end
- 稍微復雜一點的是delegate模式饶号,不巧的是UIKit很多控件都是用的代理模式實現(xiàn)铁追。把一個代理模式的API封裝成signal,對外不需要實現(xiàn)協(xié)議只使用signal - block茫船,那就需要內(nèi)部自己管理一個代理琅束。RAC為這種場景寫了一個類RACDelegateProxy:
// A private delegate object suitable for using
// -rac_signalForSelector:fromProtocol: upon.
@interface RACDelegateProxy : NSObject
// The delegate to which messages should be forwarded if not handled by
// any -signalForSelector: applications.
@property (nonatomic, unsafe_unretained) id rac_proxiedDelegate;
// Creates a delegate proxy capable of responding to selectors from `protocol`.
- (instancetype)initWithProtocol:(Protocol *)protocol;
// Calls -rac_signalForSelector:fromProtocol: using the `protocol` specified
// during initialization.
- (RACSignal *)signalForSelector:(SEL)selector;
@end
從注釋看,它的使用很簡單算谈,初始化方法傳入要代理的協(xié)議Protocol 涩禀; rac_proxiedDelegate是原代理,signalForSelector用于生成對應協(xié)議方法的signal然眼。
所以RACDelegateProxy的關(guān)鍵在signalForSelector的實現(xiàn):
- (RACSignal *)signalForSelector:(SEL)selector {
return [self rac_signalForSelector:selector fromProtocol:_protocol];
}
這里的 rac_signalForSelector : fromProtocol 在NSObject (RACSelectorSignal)分類中:
- (RACSignal *)rac_signalForSelector:(SEL)selector fromProtocol:(Protocol *)protocol {
NSCParameterAssert(selector != NULL);
NSCParameterAssert(protocol != NULL);
return NSObjectRACSignalForSelector(self, selector, protocol);
}
- (RACSignal *)rac_signalForSelector:(SEL)selector {
NSCParameterAssert(selector != NULL);
return NSObjectRACSignalForSelector(self, selector, NULL);
}
有協(xié)議和無協(xié)議的都會調(diào)用NSObjectRACSignalForSelector艾船,這是這個分類的核心方法,它里面包含的代碼比較長高每,我分解了幾塊來看屿岂,首先是RACSwizzleClass:
從它的命名猜測,應該是swizzle了類里面的一些方法觉义,返回一個Class
(這部分源碼略蛋疼雁社,我后面畫有一張圖)
static Class RACSwizzleClass(NSObject *self) {
Class statedClass = self.class;
Class baseClass = object_getClass(self);
// The "known dynamic subclass" is the subclass generated by RAC.
// It's stored as an associated object on every instance that's already
// been swizzled, so that even if something else swizzles the class of
// this instance, we can still access the RAC generated subclass.
Class knownDynamicSubclass = objc_getAssociatedObject(self, RACSubclassAssociationKey);
if (knownDynamicSubclass != Nil) return knownDynamicSubclass;
NSString *className = NSStringFromClass(baseClass);
if (statedClass != baseClass) {
// If the class is already lying about what it is, it's probably a KVO
// dynamic subclass or something else that we shouldn't subclass
// ourselves.
//
// Just swizzle -forwardInvocation: in-place. Since the object's class
// was almost certainly dynamically changed, we shouldn't see another of
// these classes in the hierarchy.
//
// Additionally, swizzle -respondsToSelector: because the default
// implementation may be ignorant of methods added to this class.
@synchronized (swizzledClasses()) {
if (![swizzledClasses() containsObject:className]) {
RACSwizzleForwardInvocation(baseClass);
RACSwizzleRespondsToSelector(baseClass);
RACSwizzleGetClass(baseClass, statedClass);
RACSwizzleGetClass(object_getClass(baseClass), statedClass);
RACSwizzleMethodSignatureForSelector(baseClass);
[swizzledClasses() addObject:className];
}
}
return baseClass;
}
const char *subclassName = [className stringByAppendingString:RACSubclassSuffix].UTF8String;
Class subclass = objc_getClass(subclassName);
if (subclass == nil) {
subclass = objc_allocateClassPair(baseClass, subclassName, 0);
if (subclass == nil) return nil;
RACSwizzleForwardInvocation(subclass);
RACSwizzleRespondsToSelector(subclass);
RACSwizzleGetClass(subclass, statedClass);
RACSwizzleGetClass(object_getClass(subclass), statedClass);
RACSwizzleMethodSignatureForSelector(subclass);
objc_registerClassPair(subclass);
}
object_setClass(self, subclass);
objc_setAssociatedObject(self, RACSubclassAssociationKey, subclass, OBJC_ASSOCIATION_ASSIGN);
return subclass;
}
替換了這個類的forwardInvocation、respondsToSelector晒骇、class霉撵、methodSignatureForSelector這幾個方法,就像它注釋所說洪囤,這里的實現(xiàn)應該和KVO類似徒坡,KVO實現(xiàn)時會創(chuàng)建一個KVO前綴的類,如果這里還創(chuàng)建一個子類的話會影響到KVO的實現(xiàn)瘤缩。但如果class沒被修改的話為什么就要創(chuàng)建一個子類喇完,我也沒太想明白。。
這幾個swizzle方法否过,關(guān)鍵在forwardInvocation累驮,其他基本上是為它服務的:
static BOOL RACForwardInvocation(id self, NSInvocation *invocation) {
//**取到aliasSelector,以及以它為key關(guān)聯(lián)的subject對象
SEL aliasSelector = RACAliasForSelector(invocation.selector);
RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
//**如果有aliasSelector要執(zhí)行(原始的selector刻诊,邏輯在下面NSObjectRACSignalForSelector方法)
Class class = object_getClass(invocation.target);
BOOL respondsToAlias = [class instancesRespondToSelector:aliasSelector];
if (respondsToAlias) {
invocation.selector = aliasSelector;
[invocation invoke];
}
if (subject == nil) return respondsToAlias;
//**sendNext將selector的參數(shù)發(fā)出去
[subject sendNext:invocation.rac_argumentsTuple];
return YES;
}
然后就到NSObjectRACSignalForSelector這個方法:
static RACSignal *NSObjectRACSignalForSelector(NSObject *self, SEL selector, Protocol *protocol) {
//**RACAliasForSelector里面就一句話,獲取一個別名為rac_alias_前綴的selector
SEL aliasSelector = RACAliasForSelector(selector);
@synchronized (self) {
//**第一次進來是沒有的牺丙,生成之后會關(guān)聯(lián)到self上则涯,往下看
RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
if (subject != nil) return subject;
//**參見上面
Class class = RACSwizzleClass(self);
NSCAssert(class != nil, @"Could not swizzle class of %@", self);
//**生成subject并關(guān)聯(lián)到self上
subject = [[RACSubject subject] setNameWithFormat:@"%@ -rac_signalForSelector: %s", RACDescription(self), sel_getName(selector)];
objc_setAssociatedObject(self, aliasSelector, subject, OBJC_ASSOCIATION_RETAIN);
[self.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
[subject sendCompleted];
}]];
Method targetMethod = class_getInstanceMethod(class, selector);
//**如果沒有這個方法
if (targetMethod == NULL) {
const char *typeEncoding;
if (protocol == NULL) {
typeEncoding = RACSignatureForUndefinedSelector(selector);
} else {
// Look for the selector as an optional instance method.
struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
if (methodDescription.name == NULL) {
// Then fall back to looking for a required instance
// method.
methodDescription = protocol_getMethodDescription(protocol, selector, YES, YES);
NSCAssert(methodDescription.name != NULL, @"Selector %@ does not exist in <%s>", NSStringFromSelector(selector), protocol_getName(protocol));
}
typeEncoding = methodDescription.types;
}
RACCheckTypeEncoding(typeEncoding);
// 添加這個方法
// Define the selector to call -forwardInvocation:.
if (!class_addMethod(class, selector, _objc_msgForward, typeEncoding)) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"A race condition occurred implementing %@ on class %@", nil), NSStringFromSelector(selector), class],
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Invoke -rac_signalForSelector: again to override the implementation.", nil)
};
return [RACSignal error:[NSError errorWithDomain:RACSelectorSignalErrorDomain code:RACSelectorSignalErrorMethodSwizzlingRace userInfo:userInfo]];
}
} else if (method_getImplementation(targetMethod) != _objc_msgForward) {
// 如果這個方法存在复局,創(chuàng)建一個帶前綴的備份添加到class,這也是上面forwardInvocation要執(zhí)行aliasSelector的原因
// Make a method alias for the existing method implementation.
const char *typeEncoding = method_getTypeEncoding(targetMethod);
RACCheckTypeEncoding(typeEncoding);
BOOL addedAlias __attribute__((unused)) = class_addMethod(class, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), class);
// 讓原方法走forwardInvocation粟判,而forwardInvocation已經(jīng)被我們swizzle過了
// Redefine the selector to call -forwardInvocation:.
class_replaceMethod(class, selector, _objc_msgForward, method_getTypeEncoding(targetMethod));
}
return subject;
}
}
簡單來說亿昏,思路就是首先創(chuàng)建一個關(guān)聯(lián)對象subject(subject是信號的一種,熱信號和冷信號不羅列了档礁,參考文獻有詳細的解讀)角钩,這個subject關(guān)聯(lián)的key是我們要監(jiān)聽的selector(alias過的),讓真正的selector走forwardInvocation轉(zhuǎn)發(fā)事秀,然后在forwardInvocation中執(zhí)行aliasSelector(帶前綴的備份彤断,因為如果本來實現(xiàn)了這個方法的話還要給人家執(zhí)行),執(zhí)行subject的sendNext將參數(shù)發(fā)出去易迹。
只是我的一些理解宰衙,細節(jié)地方也不太明白為什么那樣去做,代碼也只看了冰山一角睹欲,以后會繼續(xù)更新供炼。
參考文章
- ReactiveCocoa Tutorial – The Definitive Introduction 比較基礎的介紹文檔,有翻譯版
- sunnyxx的技術(shù)博客 Reactive Cocoa Tutorial 對編程思想窘疮、宏的使用袋哼、底層設計講的比較深入
- 美團點評團隊博客 對冷信號與熱信號的解讀、實用案例
- ReactiveCocoa 討論會 業(yè)界使用者的評價和討論總結(jié)