近期開發(fā)RN項(xiàng)目對函數(shù)式編程有了一點(diǎn)點(diǎn)的理解,回過頭看native的函數(shù)式編程框架RAC,有點(diǎn)茅塞頓開的感覺,在此記錄下RAC源碼閱讀心得。
對于函數(shù)式編程,我個人感覺最大的好處就是代碼很緊湊,結(jié)構(gòu)簡潔而清晰。到oc語言里就是“block式”編程,舉個例子,在處理輸入框的時候比如UITextField,使用UIKit原生的API需要遵循它的協(xié)議,實(shí)現(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ù)不同情況而做出一系列反應(yīng),繼而走出迷宮;RAC的思想好比是建迷宮,在創(chuàng)建時就建立好聯(lián)系,一個事件來了會引發(fā)哪些響應(yīng)鏈,都按照創(chuàng)建好的路線傳導(dǎo),像一個精密的儀器,復(fù)雜但完整而自然。
最可見的變化就是代碼量大量減少,沒有多余的狀態(tài)變量,邏輯更清晰。
RACSignal
RAC是github開源的框架,有專門社區(qū)維護(hù),代碼的水平還是很高的。對我這種初學(xué)者說收貨很大。。里面有很多關(guān)于宏、block、runtime的高級用法,一些之前掌握不深的知識點(diǎn)都有新的理解。
首先要看的肯定是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對象。這里稍微復(fù)雜一些,但從上面分析來看,這一步要做的是執(zhí)行didSubscribe,并建立關(guān)聯(lián)在sendNext、sendError、sendCompleted時執(zhí)行訂閱者對應(yīng)的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),當(dāng)CompoundDisposable dispose時會dispose它包含的所有disposables。
2.創(chuàng)建一個subscriber,這一行看起來有點(diǎn)詭異:上一步創(chuàng)建了一個RACSubscriber對象o,現(xiàn)在用o再創(chuàng)建一個RACPassthroughSubscriber賦給o,RACPassthroughSubscriber實(shí)現(xiàn)了RACSubscriber協(xié)議,并且signal、subcriber、disposable一應(yīng)俱全,看起來這個類會維系好三者之間的關(guān)系。實(shí)際上看并沒有什么管理三者關(guān)系的代碼存在,僅有一些DTrace的東西,和Instruments有關(guān)。如果把這一行注掉,會發(fā)現(xiàn)并沒有什么影響。
3.接下來就是關(guān)鍵的部分了,執(zhí)行didSubscribe block。這里用了一個subscriptionScheduler,是專門用來執(zhí)行subscription任務(wù)的,返回一個disposable是為了能夠在任務(wù)沒執(zhí)行前能控制取消掉它,也對應(yīng)了disposable這個名字的含義。scheduler內(nèi)部是gcd實(shí)現(xiàn)的,disposable相當(dāng)于一個外部的變量控制是否執(zhí)行這個任務(wù):
- (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;
}
這樣看下來,忽略一些實(shí)現(xiàn)細(xì)節(jié),其實(shí)這些類大概都是做了兩件事:1.把block存起來;2.在合適的時機(jī)執(zhí)行它。
用一張圖簡單梳理下從創(chuàng)建signal、訂閱和發(fā)布接收的關(guān)系:RAC源碼里其實(shí)有很多值得研究和學(xué)習(xí)的地方,對宏、runtime、block的使用等。比如我們在寫RAC宏的時候
RAC(self.submitBtn, enabled) = RACObserve(self.submitBtnModel, enabled);
在寫完逗號敲property時會發(fā)現(xiàn)編譯器給出了正確的代碼提示,很神奇。具體可以看下這篇博客Reactive Cocoa Tutorial [1] = 神奇的Macros。
NSObject (RACSelectorSignal)
RAC相當(dāng)于統(tǒng)一規(guī)范了異步事件的處理。那么如何將一個異步事件的處理封裝成RACSignal的形式呢。
- 如果是block回調(diào)的API,相對比較簡單,只需要創(chuàng)建signal并在回調(diào)block中sendNext、sendComplete、sendError即可。
- 如果是target-action,比如UIControl的事件,則只需要將target設(shè)置成相應(yīng)的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
- 稍微復(fù)雜一點(diǎn)的是delegate模式,不巧的是UIKit很多控件都是用的代理模式實(shí)現(xiàn)。把一個代理模式的API封裝成signal,對外不需要實(shí)現(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用于生成對應(yīng)協(xié)議方法的signal。
所以RACDelegateProxy的關(guān)鍵在signalForSelector的實(shí)現(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:
從它的命名猜測,應(yīng)該是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這幾個方法,就像它注釋所說,這里的實(shí)現(xiàn)應(yīng)該和KVO類似,KVO實(shí)現(xiàn)時會創(chuàng)建一個KVO前綴的類,如果這里還創(chuàng)建一個子類的話會影響到KVO的實(shí)現(xiàn)。但如果class沒被修改的話為什么就要創(chuàng)建一個子類,我也沒太想明白。。
這幾個swizzle方法,關(guān)鍵在forwardInvocation,其他基本上是為它服務(wù)的:
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) {
//**第一次進(jìn)來是沒有的,生成之后會關(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是信號的一種,熱信號和冷信號不羅列了,參考文獻(xiàn)有詳細(xì)的解讀),這個subject關(guān)聯(lián)的key是我們要監(jiān)聽的selector(alias過的),讓真正的selector走forwardInvocation轉(zhuǎn)發(fā),然后在forwardInvocation中執(zhí)行aliasSelector(帶前綴的備份,因?yàn)槿绻緛韺?shí)現(xiàn)了這個方法的話還要給人家執(zhí)行),執(zhí)行subject的sendNext將參數(shù)發(fā)出去。
只是我的一些理解,細(xì)節(jié)地方也不太明白為什么那樣去做,代碼也只看了冰山一角,以后會繼續(xù)更新。
參考文章
- ReactiveCocoa Tutorial – The Definitive Introduction 比較基礎(chǔ)的介紹文檔,有翻譯版
- sunnyxx的技術(shù)博客 Reactive Cocoa Tutorial 對編程思想、宏的使用、底層設(shè)計講的比較深入
- 美團(tuán)點(diǎn)評團(tuán)隊博客 對冷信號與熱信號的解讀、實(shí)用案例
- ReactiveCocoa 討論會 業(yè)界使用者的評價和討論總結(jié)