函數式響應編程

來源:互聯網
上載者:User

標籤:

ReactiveCocoa的基本使用方法

ReactiveCocoa是github一個開源項目,是在iOS平台上對FRP的實現。FRP的核心是訊號,訊號在ReactiveCocoa(以下簡稱RAC)中是通過RACSignal來表示的,訊號是資料流,可以被綁定和傳遞。

可以把訊號想象成水龍頭,只不過裡面不是水,而是玻璃球(value),直徑跟水管的內徑一樣,這樣就能保證玻璃球是依次排列,不會出現並排的情況(資料都是線性處理的,不會出現並發情況)。水龍頭的開關預設是關的,除非有了接收方(subscriber),才會開啟。這樣只要有新的玻璃球進來,就會自動傳送給接收方。可以在水龍頭上加一個過濾嘴(filter),不符合的不讓通過,也可以加一個改動裝置,把球改變成符合自己的需求(map)。也可以把多個水龍頭合并成一個新的水龍頭(combineLatest:reduce:),這樣只要其中的一個水龍頭有玻璃球出來,這個新合并的水龍頭就會得到這個球。

 

RAC統一了對KVO、UI Event、Network request、Async work的處理,因為它們本質上都是值的變化(Values over time)。

 

替代KVO

@property(strong) NSString *username;[RACObserve(self,username) subscribeNext:^(NSString *newName){    NSLog(@"%@",newName);}];

只要username發生變化就列印出來。體現綁定和響應。

[[RACObserver(self,username) filter:^(NSString *newName) {   return [newName hasPrefix:@"j"];}] subscribeNext:^(NSString *newName) {   NSLog(@"%@",newName);}

增加一個過濾器

 

替代selector

self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) {    NSLog(@"button was pressed!");    return [RACSignal empty];}];

 

流的實現

RAC(self, timeLabel.text) = [[[RACSignal interval:1 onScheduler:[RACScheduler currentScheduler]] startWith:[NSDate date]] map:^id (NSDate *value) {   NSLog(@"value:%@", value);   NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:value];  return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)dateComponents.hour, (long)dateComponents.minute, (long)dateComponents.second];}];

  

組合

RAC(self, submitButton.enabled) = [RACSignal combineLatest:@[self.usernameField.rac_textSignal, self.passwordField.rac_textSignal] reduce:^id (NSString *userName, NSString *password) {  return @(userName.length >= 6 && password.length >= 6);}];

將usernameField和passwordField的訊號綁定在一起做reduce處理。返回一個BOOL值去跟self.submitButton.enabled進綁定。


網路請求

self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^(id sender) {    return [client logIn];}];

[self.loginCommand.executionSignals subscribeNext:^(RACSignal *loginSignal) {
  [loginSignal subscribeCompleted:^{
    NSLog(@"Logged in successfully!");
  }];
}];

  

函數式響應編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.