Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Reactive Cocoa

Reactive Cocoa

The basics of Reactive Cocoa. The tips and tricks in this presentation will cover almost all the use cases for Reactive Cocoa. Demo here: https://github.com/rob-brown/Demos/tree/master/RACDemo.

Rob Brown

March 18, 2014
Tweet

More Decks by Rob Brown

Other Decks in Technology

Transcript

  1. –Wikipedia “Functional reactive programming (FRP) is a programming paradigm for

    reactive programming using the building blocks of functional programming.”
  2. What are the building blocks of functional programming? ! reduce/fold

    map filter zip ! drop take concat and more
  3. Immutable Data Data structures can’t be modified in place Values

    are copied as needed NSArray vs. NSMutableArray
  4. Pure Functions Given input X, the function always returns Y

    Allows for many compiler-level optimizations
  5. Map 1 2 3 2 4 6 x * 2

    5 6 7 x + 4
  6. RACSignal RACSignal is a stream of data, possibly infinite Its

    values are evaluated lazily Signals are the most used objects in Reactive Cocoa
  7. RAC as KVO Advantages: No more hard-coded key paths No

    more comparing key paths Code locality Refactoring will update RAC bindings
  8. Tips and Tricks Transform the values of a signal: [signal

    map:^id(NSString * text) { return [text uppercaseString]; }];
  9. Tips and Tricks Combine the results of many signals: [RACSignal

    combineLatest:@[s1, s2] reduce: ^id(NSNumber * b1, NSNumber * b2) { return @([b1 boolValue] && [b2 boolValue]); }];
  10. Tips and Tricks Watch for when multiple tasks complete: [[RACSignal

    merge:@[signal1, signal2] subscribeCompleted:^{ NSLog(@“All done”); }];
  11. Tips and Tricks Add actions to buttons: self.button.rac_command = [[RACCommand

    alloc] initWithSignalBlock:^RACSignal *(id x) { // Code goes here };
  12. Tips and Tricks Create arbitrary signals: [RACSignal createSignal: ^RACDisposable *(id<RACSubscriber>

    subscriber) { // Send next, error, and completed // messages to subscriber }];
  13. Tips and Tricks Deliver signal results to the main thread:

    [backgroundSignal deliverOn: [RACScheduler mainThreadScheduler]];
  14. Tips and Tricks If you need to perform side effects:

    [signal doNext:^(id value) {…}]; [signal doError:^(NSError * error) {…}]; [signal doCompleted:^{…}];
  15. Tips and Tricks Limit the rate a signal can be

    evaluated: [signal throttle:10.0];