本文翻譯自 GitHub 開源框架 ReactiveCocoa 的 readme,英文原文:https://github.com/ReactiveCocoa/ReactiveCocoa
ReactiveCocoa(RAC)是一套 Objective-C 框架,靈感來自函數式響應式編程。感謝 Rheinfabrik 慷慨贊助 ReactiveCocoa 3.x 的開發。
什麼是 ReactiveCocoa?
RAC 的文件寫得很紮實,詳細說明了它是什麼、怎麼運作。想再深入一些,推薦下面這些資源:
Introduction
When to use ReactiveCocoa
Framework Overview
Basic Operators
Header documentation
已回答過的 Stack Overflow 問題與 GitHub issues
Documentation 文件夾裡的其餘內容
Functional Reactive Programming on iOS(eBook)
若還有其他疑問,歡迎隨時提出 issue。
介紹
RAC 的核心想法是:不再依賴那些被反覆替換、原地修改的可變變量,而是用 signal(表現為 RACSignal)來承載「當前值」以及「未來值」。
透過對 signal 進行接線、綁定與響應,你不必再手動持續觀察並更新各處的值,程式自然就能保持同步。
舉個例子:一個 text field 可以直接綁定到某個狀態上,即使那個狀態不斷變化,也不需要額外寫程式碼去逐秒刷新 text field。這有點像 KVO,但差別在於 RAC 用 block 取代了覆寫 -observeValueForKeyPath:ofObject:change:context:。
Signal 也能用來表達異步操作,概念上近似 futures 與 promises,這讓異步程式(尤其是網絡相關的部分)大幅簡化。
RAC 最大的價值在於:它提供了一套統一的方式來處理各種異步行為,包括 delegate 方法、block 回調、target-action、通知與 KVO。
看一個簡單例子:
// When self.username changes, logs the new name to the console. // // RACObserve(self, username) creates a new RACSignal that sends the current // value of self.username, then the new value whenever it changes. // -subscribeNext: will execute the block whenever the signal sends a value. [RACObserve(self, username) subscribeNext:^(NSString *newName) { NSLog(@"%@", newName); }];與 KVO 通知不同,signal 可以串接起來一起運算:
// Only logs names that starts with "j". // // -filter returns a new RACSignal that only sends a new value when its block // returns YES. [[RACObserve(self, username) filter:^(NSString *newName) { return [newName hasPrefix:@"j"]; }] subscribeNext:^(NSString *newName) { NSLog(@"%@", newName); }];Signal 也能用來「導出」狀態。與其觀察屬性、再回頭設定其他屬性來反映新值,RAC 讓「用 signal 與運算符來定義派生屬性」成為可能:
// Creates a one-way binding so that self.createEnabled will be // true whenever self.password and self.passwordConfirmation // are equal. // // RAC() is a macro that makes the binding look nicer. // // +combineLatest:reduce: takes an array of signals, executes the block with the // latest value from each signal whenever any of them changes, and returns a new // RACSignal that sends the return value of that block as values. RAC(self, createEnabled) = [RACSignal combineLatest:@[ RACObserve(self, password), RACObserve(self, passwordConfirmation) ] reduce:^(NSString *password, NSString *passwordConfirm) { return @([passwordConfirm isEqualToString:password]); }];Signal 的用武之地遠不止 KVO。比如它也能描述按鈕點擊:
// Logs a message whenever the button is pressed. // // RACCommand creates signals to represent UI actions. Each signal can // represent a button press, for example, and have additional work associated // with it. // // -rac_command is an addition to NSButton. The button will send itself on that // command whenever it's pressed. self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) { NSLog(@"button was pressed!"); return [RACSignal empty]; }];或者異步的網絡操作:
// Hooks up a "Log in" button to log in over the network. // // This block will be run whenever the login command is executed, starting // the login process. self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^(id sender) { // The hypothetical -logIn method returns a signal that sends a value when // the network request finishes. return [client logIn]; }]; // -executionSignals returns a signal that includes the signals returned from // the above block, one for each time the command is executed. [self.loginCommand.executionSignals subscribeNext:^(RACSignal *loginSignal) { // Log a message whenever we log in successfully. [loginSignal subscribeCompleted:^{ NSLog(@"Logged in successfully!"); }]; }]; // Executes the login command when the button is pressed. self.loginButton.rac_command = self.loginCommand;Signal 還能表達計時器、其他 UI 事件,或任何隨時間變化的東西。
把 signal 接線、變換之後,就能組出更複雜的異步行為。例如等一組操作全部完成後再觸發後續工作:
// Performs 2 network operations and logs a message to the console when they are // both completed. // // +merge: takes an array of signals and returns a new RACSignal that passes // through the values of all of the signals and completes when all of the // signals complete. // // -subscribeCompleted: will execute the block when the signal completes. [[RACSignal merge:@[ [client fetchUserRepos], [client fetchOrgRepos] ]] subscribeCompleted:^{ NSLog(@"They're both done!"); }];Signal 也能把異步操作順序串起來,避免 block 回調層層嵌套,這點和 futures/promises 很像:
// Logs in the user, then loads any cached messages, then fetches the remaining // messages from the server. After that's all done, logs a message to the // console. // // The hypothetical -logInUser methods returns a signal that completes after // logging in. // // -flattenMap: will execute its block whenever the signal sends a value, and // returns a new RACSignal that merges all of the signals returned from the block // into a single signal. [[[[client logInUser] flattenMap:^(User *user) { // Return a signal that loads cached messages for the user. return [client loadCachedMessagesForUser:user]; }] flattenMap:^(NSArray *messages) { // Return a signal that fetches any remaining messages. return [client fetchMessagesAfterMessage:messages.lastObject]; }] subscribeNext:^(NSArray *newMessages) { NSLog(@"New messages: %@", newMessages); } completed:^{ NSLog(@"Fetched all messages."); }];RAC 也能把異步結果直接綁到介面上:
// Creates a one-way binding so that self.imageView.image will be set as the user's // avatar as soon as it's downloaded. // // The hypothetical -fetchUserWithUsername: method returns a signal which sends // the user. // // -deliverOn: creates new signals that will do their work on other queues. In // this example, it's used to move work to a background queue and then back to the main thread. // // -map: calls its block with each user that's fetched and returns a new // RACSignal that sends values returned from the block. RAC(self.imageView, image) = [[[[client fetchUserWithUsername:@"joshaber"] deliverOn:[RACScheduler scheduler]] map:^(User *user) { // Download the avatar (this is done on a background queue). return [[NSImage alloc] initWithContentsOfURL:user.avatarURL]; }] // Now the assignment will be done on the main thread. deliverOn:RACScheduler.mainThreadScheduler];以上說明了 RAC 能做什麼,但很難說清它為何強大。用更少的程式碼、更少的樣板,把意圖表達清楚,本身就是一種價值。
想看更多示例程式碼,可以參考 C-41 或 GroceryList,這兩個都是用 ReactiveCocoa 實作的真實 iOS App;更多資訊可查閱 Documentation 文件夾。
什麼時候該用 ReactiveCocoa
乍看之下 RAC 相當抽象,不容易想像是怎麼套進具體問題的。以下幾類場景是它常見的落腳點。
處理異步或事件驅動的數據源
大量 Cocoa 開發其實都在響應使用者事件或狀態變化,寫久了程式碼很容易變成一團麵,滿地都是回調與狀態變量。
這些模式表面差異很大——UI 回調、網絡回應、KVO 通知——但本質有不少共通之處。RACSignal 把它們統一抽象出來,於是這些 API 能夠組裝在一起,用同一套方式操作。
看下面的傳統寫法:
static void *ObservationContext = &ObservationContext; - (void)viewDidLoad { [super viewDidLoad]; [LoginManager.sharedManager addObserver:self forKeyPath:@"loggingIn" options:NSKeyValueObservingOptionInitial context:ObservationContext]; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(loggedOut:) name:UserDidLogOutNotification object:LoginManager.sharedManager]; [self.usernameTextField addTarget:self action:@selector(updateLogInButton) forControlEvents:UIControlEventEditingChanged]; [self.passwordTextField addTarget:self action:@selector(updateLogInButton) forControlEvents:UIControlEventEditingChanged]; [self.logInButton addTarget:self action:@selector(logInPressed:) forControlEvents:UIControlEventTouchUpInside]; } - (void)dealloc { [LoginManager.sharedManager removeObserver:self forKeyPath:@"loggingIn" context:ObservationContext]; [NSNotificationCenter.defaultCenter removeObserver:self]; } - (void)updateLogInButton { BOOL textFieldsNonEmpty = self.usernameTextField.text.length > 0 && self.passwordTextField.text.length > 0; BOOL readyToLogIn = !LoginManager.sharedManager.isLoggingIn && !self.loggedIn; self.logInButton.enabled = textFieldsNonEmpty && readyToLogIn; } - (IBAction)logInPressed:(UIButton *)sender { [[LoginManager sharedManager] logInWithUsername:self.usernameTextField.text password:self.passwordTextField.text success:^{ self.loggedIn = YES; } failure:^(NSError *error) { [self presentError:error]; }]; } - (void)loggedOut:(NSNotification *)notification { self.loggedIn = NO; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == ObservationContext) { [self updateLogInButton]; } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } }改用 RAC 表達,會是這樣:
- (void)viewDidLoad { [super viewDidLoad]; @weakify(self); RAC(self.logInButton, enabled) = [RACSignal combineLatest:@[ self.usernameTextField.rac_textSignal, self.passwordTextField.rac_textSignal, RACObserve(LoginManager.sharedManager, loggingIn), RACObserve(self, loggedIn) ] reduce:^(NSString *username, NSString *password, NSNumber *loggingIn, NSNumber *loggedIn) { return @(username.length > 0 && password.length > 0 && !loggingIn.boolValue && !loggedIn.boolValue); }]; [[self.logInButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *sender) { @strongify(self); RACSignal *loginSignal = [LoginManager.sharedManager logInWithUsername:self.usernameTextField.text password:self.passwordTextField.text]; [loginSignal subscribeError:^(NSError *error) { @strongify(self); [self presentError:error]; } completed:^{ @strongify(self); self.loggedIn = YES; }]; }]; RAC(self, loggedIn) = [[NSNotificationCenter.defaultCenter rac_addObserverForName:UserDidLogOutNotification object:nil] mapReplace:@NO]; }串接有依賴關係的操作
依賴關係在網絡請求裡很常見:下一個請求必須等前一個完成才能發。傳統寫法往往是回調套回調:
[client logInWithSuccess:^{ [client loadCachedMessagesWithSuccess:^(NSArray *messages) { [client fetchMessagesAfterMessage:messages.lastObject success:^(NSArray *nextMessages) { NSLog(@"Fetched all messages."); } failure:^(NSError *error) { [self presentError:error]; }]; } failure:^(NSError *error) { [self presentError:error]; }]; } failure:^(NSError *error) { [self presentError:error]; }];ReactiveCocoa 讓這種模式變得非常清爽:
[[[[client logIn] then:^{ return [client loadCachedMessages]; }] flattenMap:^(NSArray *messages) { return [client fetchMessagesAfterMessage:messages.lastObject]; }] subscribeError:^(NSError *error) { [self presentError:error]; } completed:^{ NSLog(@"Fetched all messages."); }];並行執行彼此獨立的任務
要同時跑兩組獨立數據、再把結果合併,在 Cocoa 裡並不直觀,往往還得自己處理不少同步細節:
__block NSArray *databaseObjects; __block NSArray *fileContents; NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init]; NSBlockOperation *databaseOperation = [NSBlockOperation blockOperationWithBlock:^{ databaseObjects = [databaseClient fetchObjectsMatchingPredicate:predicate]; }]; NSBlockOperation *filesOperation = [NSBlockOperation blockOperationWithBlock:^{ NSMutableArray *filesInProgress = [NSMutableArray array]; for (NSString *path in files) { [filesInProgress addObject:[NSData dataWithContentsOfFile:path]]; } fileContents = [filesInProgress copy]; }]; NSBlockOperation *finishOperation = [NSBlockOperation blockOperationWithBlock:^{ [self finishProcessingDatabaseObjects:databaseObjects fileContents:fileContents]; NSLog(@"Done processing"); }]; [finishOperation addDependency:databaseOperation]; [finishOperation addDependency:filesOperation]; [backgroundQueue addOperation:databaseOperation]; [backgroundQueue addOperation:filesOperation]; [backgroundQueue addOperation:finishOperation];同樣的需求,用 signal 合成可以寫得更乾淨:
RACSignal *databaseSignal = [[databaseClient fetchObjectsMatchingPredicate:predicate] subscribeOn:[RACScheduler scheduler]]; RACSignal *fileSignal = [RACSignal startEagerlyWithScheduler:[RACScheduler scheduler] block:^(id subscriber) { NSMutableArray *filesInProgress = [NSMutableArray array]; for (NSString *path in files) { [filesInProgress addObject:[NSData dataWithContentsOfFile:path]]; } [subscriber sendNext:[filesInProgress copy]]; [subscriber sendCompleted]; }]; [[RACSignal combineLatest:@[ databaseSignal, fileSignal ] reduce:^ id (NSArray *databaseObjects, NSArray *fileContents) { [self finishProcessingDatabaseObjects:databaseObjects fileContents:fileContents]; return nil; }] subscribeCompleted:^{ NSLog(@"Done processing"); }];簡化集合轉換
map、filter、fold/reduce 這類高階操作在 Foundation 裡相當匱乏,於是常見到這種以迴圈堆疊的寫法:
NSMutableArray *results = [NSMutableArray array]; for (NSString *str in strings) { if (str.length < 2) { continue; } NSString *newString = [str stringByAppendingString:@"foobar"]; [results addObject:newString]; }RACSequence 讓 Cocoa 集合可以用統一風格操作:
RACSequence *results = [[strings.rac_sequence filter:^ BOOL (NSString *str) { return str.length >= 2; }] map:^(NSString *str) { return [str stringByAppendingString:@"foobar"]; }];系統要求
ReactiveCocoa 需要 OS X 10.8+ 以及 iOS 8.0+。
引入 ReactiveCocoa
把 RAC 加入你的應用:
1. 將 ReactiveCocoa 倉庫作為子模塊加入你的應用倉庫。
2. 在 ReactiveCocoa 文件夾中執行 script/bootstrap。
3. 把 ReactiveCocoa.xcodeproj 拖進應用的 Xcode project 或 workspace。
4. 在應用 target 的 Build Phases 中,把 RAC 加入 Link Binary With Libraries。iOS 加 libReactiveCocoa-iOS.a;OS X 加 ReactiveCocoa.framework。RAC 還必須加入 Copy Frameworks,若沒有則選 Copy Files 並指定 Frameworks。
5. 把 "$(BUILD_ROOT)/../IntermediateBuildFilesPath/UninstalledProducts/include" 與 $(inherited) 加入 Header Search Paths(archive build 需要,平時也無妨)。
6. iOS target 需在 Other Linker Flags 加入 -ObjC。
7. 若你把 RAC 加進的是 project 而非 workspace,還需相應地把 RAC target 加入應用的 Target Dependencies。
如果你偏好 CocoaPods,社群中有第三方貢獻的 ReactiveCocoa podspec 可用。
想看實際用 RAC 寫的專案,可以參考 C-41 或 GroceryList。
獨立開發
如果你的工作只是單純修改 RAC 本身,而不是把它集成進另一個專案,建議打開 ReactiveCocoa.xcworkspace 而非 .xcodeproj。
更多資訊
ReactiveCocoa 的靈感來自 .NET 的 Reactive Extensions(Rx),Rx 的許多原則同樣適用於 RAC。不錯的 Rx 資源包括:
Reactive Extensions MSDN entry
Reactive Extensions for .NET Introduction
Rx - Channel 9 videos
Reactive Extensions wiki
101 Rx Samples
Programming Reactive Extensions and LINQ
RAC 與 Rx 都源自函數式響應式編程,以下資源關於 FRP:
What is FRP? - Elm Language
What is Functional Reactive Programming - Stack Overflow
Specification for a Functional Reactive Language - Stack Overflow
Escape from Callback Hell
Principles of Reactive Programming on Coursera