This document discusses functional reactive programming (FRP) and compositional event systems as an alternative to callback-based programming for handling asynchronous events. It notes several problems with callback-based approaches, including unpredictable order, missing events, and messy state. FRP models computations as transformations of values over time using signals, which can represent asynchronous data streams and be composed using higher-order functions like map, filter, and flatMap. This allows asynchronous code to be written in a declarative, pure, thread-safe and composable way without explicit state management. However, the document cautions that FRP is not a silver bullet and there are still challenges around distinguishing hot and cold signals.
3. WHY?
The world is asynchronous
Programs need to interact with the world
4. But we have Listeners/Observer/Delegate/Callback
Patterns! Life's good! Go away!
5. // Yeah, the empire still uses Objective C
@protocol DeathStarDelegate {
- (void)didBlowUp;
}
// In DeathStar
@property (nonatomic, weak) id <DeathStarDelegate> delegate
// When Blowing up
[self.delegate didBlowUp];
// In DarthVader who implements DeathStarDelegate
- (void)didBlowUp {
NSLog(@"Need to hire better stormtroopers");
}
8. "our intellectual powers are rather geared to master static
relations and that our powers to visualize processes
evolving in time are relatively poorly developed"
Dijkstra on GOTO
10. Imperative programming describes computations as a series
of actions modifying program state
var numbers = [1,2,3,4,5];
var even = [];
numbers.forEach(function(n) {
if (n % 2 == 0) {
even.push(n);
}
});
console.log(even);
11. In functional programming we describe what we want rather
than how we want it done
var numbers = [1,2,3,4,5];
var even = numbers.filter(function(n){
return n % 2 == 0;
});
12. In FP we model computations as transformations of values
Declarative
Pure
Threadsafe
Composable
14. SIGNALS
Representing a stream of values (over time)
e.g Async operations like API calls/UI Input/Timer RETURN
Signals
Sends three kinds of events
Next
Error
Completed
15. Signals can be subscribed to
[lannisterSignal subscribeNext:^(NSString *name){
NSLog(@"%@ is a true Lannister", name);
}];
[lannisterSignal sendNext:@"Cersei"];
[lannisterSignal sendNext:@"Jamie"];
[lannisterSignal sendCompleted];
[lannisterSignal sendNext:@"Tyrion"]; // Nothing logged here. Sorry Tyrion