ReactiveCocoa 學(xué)習(xí)筆記

近期開發(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ù)更新。


參考文章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內(nèi)容