您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

ReactiveCocoa v2.5 源碼解析(一):四大核心組件與整體架構總覽

編輯:iOS 開發基礎

ReactiveCocoa 是 iOS 上一個函數式響應式編程框架,靈感來自 Functional Reactive Programming。它由 Justin Spahr-Summers 和 Josh Abernathy 在開發 GitHub for Mac 的過程中誕生,提供了一系列用於組合和轉換值流的 API。

Mattt Thompson 是這樣評價它的:

Breaking from a tradition of covering Apple APIs exclusively, this edition of NSHipster will look at an open source project that exemplifies this brave new era for Objective-C.

他認為 ReactiveCocoa 打破了蘋果 API 的排他性,開創了 Objective-C 的新紀元,具有劃時代意義。對一個第三方框架來說,這已經是極高的評價。

版本演進大致如下:

  • <= v2.5:Objective-C
  • v3.x:Swift 1.2
  • v4.x:Swift 2.x

注:本文內容均基於 ReactiveCocoa v2.5,這是 Objective-C 最新的穩定版本。文章結構如下:簡介、信號源(RACStream / RACSignal / RACSubject / RACSequence)、訂閱者(RACSubscriber / RACMulticastConnection)、調度器(RACScheduler)、清潔工(RACDisposable)、總結與參考鏈接。

簡介

這是一個相當複雜的框架。在深入核心組件之前,先看類圖,從宏觀上把握它的層次結構:

從類圖可以看出,ReactiveCocoa 主要由四大核心組件構成:

  • 信號源:RACStream 及其子類
  • 訂閱者:RACSubscriber 的實現類及其子類
  • 調度器:RACScheduler 及其子類
  • 清潔工:RACDisposable 及其子類

其中信號源是最核心的部分,其他組件都圍繞它運作。

對一個應用來說,絕大多數時間都花在等待事件發生或響應狀態變化上:用戶的觸摸、App 進入後台、網絡請求回來後刷新界面……而維護這些狀態變化常常讓代碼變得複雜難擴展。ReactiveCocoa 的方案是用信號代表這些異步事件,提供一種統一的方式處理所有異步行為,包括代理方法、block 回調、target-action、通知、KVO:

// 代理方法
[[self
    rac_signalForSelector:@selector(webViewDidStartLoad:)
    fromProtocol:@protocol(UIWebViewDelegate)]
    subscribeNext:^(id x) {
        // 實現 webViewDidStartLoad: 代理方法
    }];

// target-action
[[self.avatarButton
    rac_signalForControlEvents:UIControlEventTouchUpInside]
    subscribeNext:^(UIButton *avatarButton) {
        // avatarButton 被點擊了
    }];

// 通知
[[[NSNotificationCenter defaultCenter]
    rac_addObserverForName:kReachabilityChangedNotification object:nil]
    subscribeNext:^(NSNotification *notification) {
        // 收到 kReachabilityChangedNotification 通知
    }];

// KVO
[RACObserve(self, username) subscribeNext:^(NSString *username) {
    // 用戶名發生了變化
}];

但這些還只是冰山一角。它真正強大的地方在於:這些不同的信號可以被任意組合與鏈式操作,從最原始的輸入一路流到最終的輸出:

[[[RACSignal
    combineLatest:@[ RACObserve(self, username), RACObserve(self, password) ]
    reduce:^(NSString *username, NSString *password) {
        return @(username.length > 0 && password.length > 0);
    }]
    distinctUntilChanged]
    subscribeNext:^(NSNumber *valid) {
        if (valid.boolValue) {
            // 用戶名和密碼合法,登錄按鈕可用
        } else {
            // 用戶名或密碼不合法,登錄按鈕不可用
        }
    }];

所以毫不誇張地說,阻礙 ReactiveCocoa 發揮的瓶頸只剩下你的想象力。

信號源

信號源代表的是隨時間變化的值流,這是對 ReactiveCocoa 最精準的概括,訂閱者通過訂閱信號源獲取這些值:

Streams of values over time.

你可以把它想象成水龍頭裡的水,打開就源源不斷;也可以想象成電,插上插頭就靜靜流入手機;還可以想象成運送玻璃珠的管道,打開閥門珠子一個接一個到達。水、電、玻璃珠就是我們需要的值,而打開水龍頭、插上插頭、打開閥門就是訂閱的過程。

RACStream

RACStream 是整個框架最核心的類,代表任意的值流,是 ReactiveCocoa 得以建立的基石。繼承結構如下:

它其實是一個抽象類,通常我們不會直接實例化它,而是使用它的兩個子類 RACSignal 和 RACSequence。那麼問題來了:為什麼 RACStream 要被設計成抽象類?抽象的依據是什麼?

讀過我上一篇《Functor、Applicative 和 Monad》的同學應該已經有答案了——RACStream 就是以 Monad 的概念為依據設計的,它代表的就是一個 Monad:

/// An abstract class representing any stream of values.
///
/// This class represents a monad, upon which many stream-based operations can
/// be built.
///
/// When subclassing RACStream, only the methods in the main @interface body need
/// to be overridden.
@interface RACStream : NSObject

/// Lifts `value` into the stream monad.
///
/// Returns a stream containing only the given value.
+ (instancetype)return:(id)value;

/// Lazily binds a block to the values in the receiver.
///
/// This should only be used if you need to terminate the bind early, or close
/// over some state. -flattenMap: is more appropriate for all other cases.
///
/// block - A block returning a RACStreamBindBlock. This block will be invoked
///         each time the bound stream is re-evaluated. This block must not be
///         nil or return nil.
///
/// Returns a new stream which represents the combined result of all lazy
/// applications of `block`.
- (instancetype)bind:(RACStreamBindBlock (^)(void))block;

@end

有了 Monad 這個基石,許多基於流的操作就能被建立起來,比如 map、filter、zip。

RACSignal

RACSignal 代表未來將會被傳送的值,是一種 push-driven 的流。它向訂閱者發送三種類型的事件:

  • next:傳送一個新的值,該值可以為 nil
  • error:表明信號在正常結束前發生了錯誤
  • completed:表明信號已正常結束,不會再有後續值

注意,ReactiveCocoa 所說的「值流」只包含正常的值,即通过 next 傳送的值,不包括 error 和 completed,它們需要被特殊處理。通常一個信號的生命周期由任意個 next 加一個 error 或一個 completed 組成。

從類圖可以看出,RACSignal 並非只有一個類,它的各項功能是通過類簇實現的。除去下節要講的 RACSubject 系列,還有五個私有子類:

  • RACEmptySignal:空信號,實現 +empty
  • RACReturnSignal:一元信號,實現 +return:
  • RACDynamicSignal:動態信號,用一個 block 實現訂閱行為,+createSignal: 創建的就是它的實例
  • RACErrorSignal:錯誤信號,實現 +error:
  • RACChannelTerminal:通道終端,代表 RACChannel 的一端,用於雙向綁定

整個類簇最核心的方法是 -subscribe:,它封裝了訂閱者對信號源的一次訂閱過程,是訂閱者與信號源產生聯繫的唯一入口。因此每個子類對這個方法的實現邏輯,就代表了該子類的具體訂閱行為,也是區分不同子類的關鍵。這也是為什麼 RACSignal 中的 -subscribe: 是抽象方法、必須由子類實現:

- (RACDisposable *)subscribe:(id)subscriber {
    NSCAssert(NO, @"This method must be overridden by subclasses");
    return nil;
}

RACSubject

RACSubject 代表可以手動控制的信號,你可以把它看作 RACSignal 的可變版本,就像 NSMutableArray 之於 NSArray。

它繼承自 RACSignal,所以能作為信號源被訂閱;同時又實現了 RACSubscriber 協議,所以也能作為訂閱者去訂閱其他信號源——這正是它可以被手動控制的原因:

按官方 Design Guidelines 的說法,我們應該盡可能少用它。因為它太靈活,任何時候任何地方都能操作,一旦過度使用,代碼就會變得難以理解。

根據我的實踐經驗,在 MVVM 中用 RACSubject 實現統一錯誤處理非常順手。比如在 viewModel 基類中聲明一個 RACSubject 類型的 errors 屬性,然後在 viewController 基類裡寫一次統一處理:

[self.viewModel.errors subscribeNext:^(NSError *error) {
    // 錯誤處理邏輯
}];

這樣一來,假設某個界面的 viewModel 裡有三個請求遠程數據的命令:requestReadmeMarkdownCommand、requestBlobCommand、requestReadmeHTMLCommand,那麼該界面的錯誤處理只需合併這三條錯誤流:

[[RACSignal
    merge:@[
        self.requestReadmeMarkdownCommand.errors,
        self.requestBlobCommand.errors,
        self.requestReadmeHTMLCommand.errors
    ]]
    subscribe:self.errors];

RACSubject 本身也有三個子類:

  • RACGroupedSignal:分組信號,實現 RACSignal 的分組功能
  • RACBehaviorSubject:重演最後值的信號,被訂閱時會把最後接收到的值發給訂閱者
  • RACReplaySubject:重演信號,保存發送過的值,被訂閱時重新發送一遍

功能強大,但也太過靈活——正因如此,我們只在迫不得已時才使用它。

RACSequence

RACSequence 代表一個不可變的值序列。與 RACSignal 不同,它是 pull-driven 類型的流。嚴格來說它不算信號源,因為它不能被訂閱,但它與 RACSignal 之間可以非常方便地互轉。

理論上一個 RACSequence 由兩部分組成:

  • head:序列中的第一個對象,序列為空時是 nil
  • tail:除第一個對象外的所有其他對象,同樣在空序列時為 nil

而序列的 tail 本身仍然是一個序列。如果把序列看作一條毛毛蟲:

同樣地,一個序列的 tail 又能拆成 head 和 tail,新的 tail 又能繼續拆下去,這個遞歸過程可以一直進行。這正是 RACSequence 的理論基礎,所以一個子類的最小實現就是 head 和 tail:

/// Represents an immutable sequence of values. Unless otherwise specified, the /// sequence's values are evaluated lazily on demand. Like Cocoa collections, /// sequences cannot contain nil. /// /// Most inherited RACStream methods that accept a block will execute the block /// _at most_ once for each value that is evaluated in the returned sequence. /// Side effects are subject to the behavior described in /// +sequenceWithHeadBlock:tailBlock:. /// /// Implemented as a class cluster. A minimal implementation for a subclass /// consists simply of -head and -tail. @interface RACSequence : RACStream /// The first object in the sequence, or nil if the sequence is empty. /// /// Subclasses must provide an implementation of this method. @property (nonatomic, strong, readonly) id head; /// All but the first object in the sequence, or nil if the sequence is empty. /// /// Subclasses must provide an implementation of this method. @property (nonatomic, strong, readonly) RACSequence *tail; @end

總的來說,RACSequence 最大的意義是簡化 Objective-C 中的集合操作:

Simplifying Collection Transformations: Higher-order functions like map, filter, fold/reduce are sorely missing from Foundation.

比如這段命令式代碼:

NSMutableArray *results = [NSMutableArray array];
for (NSString *str in strings) {
    if (str.length < 2) {
        continue;
    }
    NSString *newString = [str stringByAppendingString:@"foobar"];
    [results addObject:newString];
}

用 RACSequence 可以寫得更優雅:

RACSequence *results = [[strings.rac_sequence
    filter:^ BOOL (NSString *str) {
        return str.length >= 2;
    }]
    map:^(NSString *str) {
        return [str stringByAppendingString:@"foobar"];
    }];

鏈式操作可以一直串下去,直到得到你要的最終結果。另一個主要好處是:RACSequence 中的值默認是懶計算的,只有在真正用到時才計算,而且只計算一次。也就是說,如果只用到序列的一部分值,性能就在不知不覺中受益。

同樣通過類簇實現,RACSequence 共有九個私有子類:

  • RACUnarySequence:一元序列,實現 +return:
  • RACIndexSetSequence:遍歷索引集
  • RACEmptySequence:空序列,實現 +empty
  • RACDynamicSequence:用 blocks 動態實現的序列
  • RACSignalSequence:遍歷信號中的值
  • RACArraySequence:遍歷數組元素
  • RACEagerSequence:非懶計算序列,初始化時立即算出所有值
  • RACStringSequence:遍歷字符串中的字符
  • RACTupleSequence:遍歷元組元素

類簇為使用者提供了統一的對外接口,客戶端代碼完全不需要知道私有子類的存在,實現細節被很好地隱藏了。另外值得一提的是,RACSequence 實現了快速枚舉協議 NSFastEnumeration,其中只聲明了一個看起來頗為奇觀的方法:

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len;

感興趣的同學可以看看它在 RACSequence 中的實現,後續文章會介紹。也正因為如此,我們可以直接用 for in 遍歷一個 RACSequence。

訂閱者

知道信號源是什麼之後,要拿到其中的值就得訂閱。在 ReactiveCocoa 中,訂閱者是一個抽象概念:所有實現了 RACSubscriber 協議的類都可以作為訂閱者。

RACSubscriber

協議中聲明了四個必須實現的方法:

/// Represents any object which can directly receive values from a RACSignal. /// /// You generally shouldn't need to implement this protocol. +[RACSignal /// createSignal:], RACSignal's subscription methods, or RACSubject should work /// for most uses. /// /// Implementors of this protocol may receive messages and values from multiple /// threads simultaneously, and so should be thread-safe. Subscribers will also /// be weakly referenced so implementations must allow that. @protocol RACSubscriber @required /// Sends the next value to subscribers. /// /// value - The value to send. This can be `nil`. - (void)sendNext:(id)value; /// Sends the error to subscribers. /// /// error - The error to send. This can be `nil`. /// /// This terminates the subscription, and invalidates the subscriber (such that /// it cannot subscribe to anything else in the future). - (void)sendError:(NSError *)error; /// Sends completed to subscribers. /// /// This terminates the subscription, and invalidates the subscriber (such that /// it cannot subscribe to anything else in the future). - (void)sendCompleted; /// Sends the subscriber a disposable that represents one of its subscriptions. /// /// A subscriber may receive multiple disposables if it gets subscribed to /// multiple signals; however, any error or completed events must terminate _all_ /// subscriptions. - (void)didSubscribeWithDisposable:(RACCompoundDisposable *)disposable; @end

其中 -sendNext:、-sendError:、-sendCompleted 分別對應接收 next、error、completed 事件,-didSubscribeWithDisposable: 則用來接收代表某次訂閱的 disposable 對象。

一次訂閱過程可以抽象為:通過 RACSignal 的 -subscribe: 傳入一個訂閱者,最終返回一個 RACDisposable 對象:

注意:ReactiveCocoa 中並沒有專門的 RACSubscription 類,而是間接用 RACDisposable 充當這個角色。因此一個 RACDisposable 對象就代表一次訂閱,我們可以用它來取消這次訂閱。

除了 RACSignal 的子類,還有兩個類實現了 RACSubscriber 協議:

其中 RACSubscriber 類與協議同名,這跟 NSObject 類與 NSObject 協議同名是一個道理,除了名字相同之外別無關聯。它就是那個老老實實實現了協議的真正訂閱者。

那 RACPassthroughSubscriber 又是做什麼的?原因在於:一個訂閱者可以訂閱多個信號源,因而會有多個 RACDisposable,並且要能隨時取消其中任意一個。為此 ReactiveCocoa 引入了 RACPassthroughSubscriber,它是 RACSubscriber 的裝飾器,封裝了一個真正的訂閱者,負責把事件轉發過去;一旦本次訂閱被取消,它就停止轉發:

- (void)sendNext:(id)value {
    if (self.disposable.disposed) return;
    [self.innerSubscriber sendNext:value];
}

- (void)sendError:(NSError *)error {
    if (self.disposable.disposed) return;
    [self.innerSubscriber sendError:error];
}

- (void)sendCompleted {
    if (self.disposable.disposed) return;
    [self.innerSubscriber sendCompleted];
}

實際上 ReactiveCocoa 傾向於隱藏訂閱者,因為外界根本不需要知道它的存在,那是內部實現細節。這樣做進一步簡化了訂閱邏輯,客戶端代碼只需關心它需要的值。

RACMulticastConnection

訂閱一個信號源時,往往會產生副作用或消耗較大資源,比如修改全局變量、發出網絡請求。這時候我們希望多個訂閱者共享同一次訂閱——就像高中時幾個好朋友合訂一份英語周報,只出一份錢,是一個道理。這就是 RACMulticastConnection 存在的原因。

它通過一個標志 _hasConnected 保證只對 sourceSignal 訂閱一次,然後對外暴露一個 RACSubject 類型的 signal 供外部訂閱。這樣一來,不管外部訂閱多少次,對 sourceSignal 的訂閱至多只有一次:

注:理解它的實現原理,對後面理解 -replay、replayLast、replayLazily 等方法很有幫助。

調度器

有了信號源和訂閱者,還需要一個調度器來統一安排訂閱過程中的任務,才能保證它們合理有序地執行。

RACScheduler

RACScheduler 扮演的就是這個角色。本質上它由 GCD 的串行隊列實現,並支持取消操作。值得强调的是,ReactiveCocoa 並沒有使用 NSOperationQueue 或 NSRunloop,RACScheduler 只是對 GCD 的簡單封裝。

同樣以類簇實現,除測試用子類外共有四個私有子類:

看上去子類不少,但真正幹活的主要是 RACTargetQueueScheduler:

  • RACImmediateScheduler:立即執行任務,是唯一支持同步執行的調度器
  • RACQueueScheduler:抽象的隊列調度器,在一個 GCD 串行隊列中異步調度所有任務
  • RACTargetQueueScheduler:繼承自 RACQueueScheduler,在以任意 GCD 隊列為 target 的串行隊列中異步調度任務
  • RACSubscriptionScheduler:只用來調度訂閱

還有一個非常特殊的方法值得單獨說:

- (RACDisposable *)scheduleRecursiveBlock:(RACSchedulerRecursiveBlock)recursiveBlock;

它能將遞歸調用轉換成迭代調用,目的是解決深層遞歸可能帶來的堆棧溢出問題。

清潔工

既然訂閱過程可能產生副作用或消耗資源,那麼在取消訂閱或完成訂閱時,就需要做一些資源回收和垃圾清理。

RACDisposable

RACDisposable 就是這個清潔工,它封裝了取消和清理一次訂閱所必需的工作。核心方法是 -dispose,調用後執行相應清理,有點類似 NSObject 的 -dealloc。它共有四個子類:

  • RACSerialDisposable:作為容器使用,可包含一個 disposable,並允許通過原子操作把它替換出來
  • RACKVOTrampoline:代表一次 KVO 觀察,可用來停止觀察
  • RACCompoundDisposable:同樣是容器,但可以包含多個 disposable,支持手動添加與移除,有點像 NSMutableArray。當它被 disposed 時,會調用所含所有 disposable 的 -dispose,作用類似 autoreleasepool
  • RACScopedDisposable:在自身 dealloc 時調用 -dispose

初看邏輯有些複雜,但換湯不換藥——不管怎麼變換形式,最終目的都是在合適的時機調用 disposable 的 -dispose,完成清理。

總結

至此,ReactiveCocoa 的四大核心組件介紹完了,我們也對它的架構有了宏觀認識:它建立在 Monad 概念之上,圍繞這塊基石搭建了一整套配套組件,共同支撐起它的強大功能。

雖然它是一個重型的函數響應式框架,但並不會對現有代碼構成侵略性——你完全可以在單獨一個類裡使用它,哪怕只是一行代碼也沒問題。所以如果你對 ReactiveCocoa 感興趣,不妨現在就開始嘗試,Let's go!

PS:MVVMReactiveCocoa 是我用 MVVM + RAC 編寫的一個開源應用,有興趣可以 clone 下來看看 ReactiveCocoa 的具體實踐。

參考鏈接

https://github.com/ReactiveCocoa/ReactiveCocoa/tree/v2.5
https://github.com/ReactiveCocoa/ReactiveCocoa/blob/v2.5/Documentation/FrameworkOverview.md
https://github.com/ReactiveCocoa/ReactiveCocoa/blob/v2.5/Documentation/DesignGuidelines.md#avoid-using-subjects-when-possible
https://nshipster.com/reactivecocoa/
https://nathanli.cn/2015/08/27/reactivecocoa2-源碼淩析/
https://blog.devtang.com/blog/2014/02/11/reactivecocoa-introduction/
https://m.oschina.net/blog/294178

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved