<commit_before># ReactiveCocoa
ReactiveCocoa (RAC) is a framework for composing and transforming sequences of values. (It's more or less and Objective-C version of .NET's [Reactive Extensions](http://msdn.microsoft.com/en-us/data/gg577609) (Rx).)

See the announcement blogpost for a quick intro: [ReactiveCocoa is now open source](https://github.com/blog/1107-reactivecocoa-is-now-open-source).

## Intro
The fundamental ideas of RAC are pretty straightforward. It's all about subscribables. You can think of them as the evil twin of enumerables. With enumerables, you walk across some collection—item by item—until you manually stop, you hit the end of the collection, or something bad happens.

With subscribables, you subscribe to it and it then feeds you items—one by one—until you manually stop, the subscribable completes, or something bad happens.

This is often described in the Rx world as enumeration being pull while subscribing is push. Instead of asking for items, you're fed items.

Pretty straightforward right? So what's the big deal?

## The Big Deal™
It turns out this subscribable behavior is really useful in a lot of different cases. And it's extraordinarily useful especially once you start composing subscribables.

## Examples
Enough words. Let's see some code:

```obj-c
[RACAbleSelf(self.username) subscribeNext:^(NSString *newName) {
		NSLog(@"%@", newName);
	}];
```

That creates a subscribable from `self`'s KVO-compliant property `username` and logs the new value whenever it changes.

That's nice but the real power comes when we compose subscribables. Like so:

```obj-c
[[RACAbleSelf(self.username) 
	where:^(NSString *newName) {
		return [newName isEqualToString:@"joshaber"];
	}] 
	subscribeNext:^(id _) {
		NSLog(@"Hi me!");
	}];
```

So now we're logging "Hi me!" whenever the username is "joshaber." Cool, but we can do better:

```obj-c
[[[[RACAbleSelf(self.username) 
	distinctUntilChanged] 
	take:3] 
	where:^(NSString *newName) {
		return [newName isEqualToString:@"joshaber"];
	}] 
	subscribeNext:^(id _) {
		NSLog(@"Hi me!");
	}];
```

Holy composed subscribables Batman! So we're now only being notified if the new value isn't the same as the old value, and we're only giving them 3 tries to be me.

We can even combine subscribables. Suppose we have a view where they create an account, and we want to only enable the "Create" button when the password and password confirmation fields match.

```obj-c
[[RACSubscribable 
	combineLatest:[NSArray arrayWithObjects:RACAbleSelf(self.password), RACAbleSelf(self.passwordConfirmation), nil] 
	reduce:^(RACTuple *values) {
		NSString *currentPassword = [values objectAtIndex:0];
		NSString *currentConfirmPassword = [values objectAtIndex:1];
		return [NSNumber numberWithBool:[currentConfirmPassword isEqualToString:currentPassword]];
	}] 
	subscribeNext:^(NSNumber *match) {
		self.createEnabled = [match boolValue];
	}];
```

So any time our `password` or `passwordConfirmation` properties change, we reduce them to a BOOL of whether or not they match. Then we enable or disable the create button with that result.

### Isn't this just KVO?
Only kinda. It's like KVO in that it's a way of being told when things change. But it's really much more general, flexible, and usable than KVO. That said, it **does** leverage KVO. As you can see above, for instance, you can create a subscribable from a KVO-compliant property.

### Yeah but I can already do all that myself
Sure, but by using RAC you get some pretty awesome stuff for free:

1. No state. If we did it ourselves, we'd have to keep and manage quite a bit of state manually. Therein lies bugs.
1. Code locality. If we did it manually, the code would be spread out across many different method calls. This way we define the behavior all in one place.
1. Better expression of intent. RAC allows us to more clearly express our _intent_ rather than worrying about the specific implementation details.

## Async
The subscribable paradigm also fits quite nicely with async operations. Your async calls return subscribables which lets you leverage all the power of composing subscribable operations.

For example, to call a block once multiple async operations have completed:

``` obj-c
[[RACSubscribable 
	merge:[NSArray arrayWithObjects:[client fetchUserRepos], [client fetchOrgRepos], nil]] 
	subscribeCompleted:^{
		NSLog(@"They're both done!");
	}];
```

Or to chain async operations:

``` obj-c
[[[[client 
	loginUser] 
	selectMany:^(id _) {
		return [client fetchMessages];
	}]
	selectMany:^(Message *message) {
		return [client fetchFullMessage:message];
	}]
	subscribeNext:^(Message *fullMessage) {
		NSLog(@"Got message: %@", fullMessage);
	} 
	completed:^{
		NSLog(@"Fetched all messages.");
	}];
```

That will login, then fetch messages, then for each message fetched, fetch the full message, log each full message and then log when it's all done.

## Bindings
Bindings let you use RAC to drive your user interface. See the [Mac sample project](https://github.com/github/ReactiveCocoa/tree/master/GHAPIDemo/GHAPIDemo).

But iOS doesn't have bindings. Thankfully, RAC's KVO wrapping makes it easy to bind to KVC-compliant properties a RAC subscribable. It looks like this:

``` obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.someLabel.text) to:RACAbleSelf(self.someText)];
```

The real beauty of this is that we could also use any RAC operations on the subscribable to which it is bound. For example, to transform the new value before propagating it to the bound object:

``` obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.someLabel.text) to:[RACAbleSelf(self.someText) select:^(NSString *newText) {
	return [newText uppercaseString];
}]];
```

Unfortunately, a lot of UIKit classes don't expose KVO-compliant properties. `UITextField`'s `text` property, for example, isn't KVO-compliant. For cases like that, we added `-[UIControl rac_subscribableForControlEvents:]` which sends a new value every time the control events fire.

To go even one step further, we wrapped that in a property on `UITextField` so you can just use `-[UITextField rac_textSubscribable]` to watch for changes to `text`. Now we can write:

```obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.username) to:self.usernameField.rac_textSubscribable];
```

Our `username` property is now bound to the value of our `usernameField` text field.

See the [iOS sample project](https://github.com/github/ReactiveCocoa/tree/master/RACiOSDemo) for an example.

## Lifetime
The point of RAC is to make your life better as a programmer. To that end, `RACSubscribable`'s lifetime is a little funny.

RAC will keep subscribables alive for as long as they need in order to deliver events to its subscribers. This means you usually don't need to worry about keeping a strong reference to a subscribable. RAC will manage it for you.

RAC cleans up a subscribable when:

1. The subscribable sends an error or is completed, or
1. When all its subscribers have unsubscribed and it receives no new subscribers after one runloop iteration.

If you want to keep a subscribable alive past either of those cases, you need to keep a strong reference to it. But you shouldn't usually need to do that.

### KVO
KVO is a special case when it comes to lifetime. Subscribables created from a KVO-compliant property are kept alive for the lifetime of the source object. As such, they never really 'complete.' Instead, when the source object is dealloc'd, the subscribable removes all its subscribers and gets released.

### Disposables
The `-[RACSubscribable subscribe:]` method returns a `RACDisposable`. That disposable encapsulates the tasks necessary to stop and clean up the subscription. You can call `-dispose` on a disposable to end your subscription manually. Typically you won't need to manually track or dispose of disposables. They're automatically called by RAC as part of the subscribable's lifecycle.

## It's ugly!
Beauty is in the eye of the beholder! We've played with a lot of different formatting styles to try to find one that's both concise and readable. The examples are in the style we currently use.

That said, it's also a matter of getting used to what a different kind of code looks like. Give it time. It might grow on you.<commit_msg>license<commit_after># ReactiveCocoa
ReactiveCocoa (RAC) is a framework for composing and transforming sequences of values. (It's more or less and Objective-C version of .NET's [Reactive Extensions](http://msdn.microsoft.com/en-us/data/gg577609) (Rx).)

See the announcement blogpost for a quick intro: [ReactiveCocoa is now open source](https://github.com/blog/1107-reactivecocoa-is-now-open-source).

## Intro
The fundamental ideas of RAC are pretty straightforward. It's all about subscribables. You can think of them as the evil twin of enumerables. With enumerables, you walk across some collection—item by item—until you manually stop, you hit the end of the collection, or something bad happens.

With subscribables, you subscribe to it and it then feeds you items—one by one—until you manually stop, the subscribable completes, or something bad happens.

This is often described in the Rx world as enumeration being pull while subscribing is push. Instead of asking for items, you're fed items.

Pretty straightforward right? So what's the big deal?

## The Big Deal™
It turns out this subscribable behavior is really useful in a lot of different cases. And it's extraordinarily useful especially once you start composing subscribables.

## Examples
Enough words. Let's see some code:

```obj-c
[RACAbleSelf(self.username) subscribeNext:^(NSString *newName) {
		NSLog(@"%@", newName);
	}];
```

That creates a subscribable from `self`'s KVO-compliant property `username` and logs the new value whenever it changes.

That's nice but the real power comes when we compose subscribables. Like so:

```obj-c
[[RACAbleSelf(self.username) 
	where:^(NSString *newName) {
		return [newName isEqualToString:@"joshaber"];
	}] 
	subscribeNext:^(id _) {
		NSLog(@"Hi me!");
	}];
```

So now we're logging "Hi me!" whenever the username is "joshaber." Cool, but we can do better:

```obj-c
[[[[RACAbleSelf(self.username) 
	distinctUntilChanged] 
	take:3] 
	where:^(NSString *newName) {
		return [newName isEqualToString:@"joshaber"];
	}] 
	subscribeNext:^(id _) {
		NSLog(@"Hi me!");
	}];
```

Holy composed subscribables Batman! So we're now only being notified if the new value isn't the same as the old value, and we're only giving them 3 tries to be me.

We can even combine subscribables. Suppose we have a view where they create an account, and we want to only enable the "Create" button when the password and password confirmation fields match.

```obj-c
[[RACSubscribable 
	combineLatest:[NSArray arrayWithObjects:RACAbleSelf(self.password), RACAbleSelf(self.passwordConfirmation), nil] 
	reduce:^(RACTuple *values) {
		NSString *currentPassword = [values objectAtIndex:0];
		NSString *currentConfirmPassword = [values objectAtIndex:1];
		return [NSNumber numberWithBool:[currentConfirmPassword isEqualToString:currentPassword]];
	}] 
	subscribeNext:^(NSNumber *match) {
		self.createEnabled = [match boolValue];
	}];
```

So any time our `password` or `passwordConfirmation` properties change, we reduce them to a BOOL of whether or not they match. Then we enable or disable the create button with that result.

### Isn't this just KVO?
Only kinda. It's like KVO in that it's a way of being told when things change. But it's really much more general, flexible, and usable than KVO. That said, it **does** leverage KVO. As you can see above, for instance, you can create a subscribable from a KVO-compliant property.

### Yeah but I can already do all that myself
Sure, but by using RAC you get some pretty awesome stuff for free:

1. No state. If we did it ourselves, we'd have to keep and manage quite a bit of state manually. Therein lies bugs.
1. Code locality. If we did it manually, the code would be spread out across many different method calls. This way we define the behavior all in one place.
1. Better expression of intent. RAC allows us to more clearly express our _intent_ rather than worrying about the specific implementation details.

## Async
The subscribable paradigm also fits quite nicely with async operations. Your async calls return subscribables which lets you leverage all the power of composing subscribable operations.

For example, to call a block once multiple async operations have completed:

``` obj-c
[[RACSubscribable 
	merge:[NSArray arrayWithObjects:[client fetchUserRepos], [client fetchOrgRepos], nil]] 
	subscribeCompleted:^{
		NSLog(@"They're both done!");
	}];
```

Or to chain async operations:

``` obj-c
[[[[client 
	loginUser] 
	selectMany:^(id _) {
		return [client fetchMessages];
	}]
	selectMany:^(Message *message) {
		return [client fetchFullMessage:message];
	}]
	subscribeNext:^(Message *fullMessage) {
		NSLog(@"Got message: %@", fullMessage);
	} 
	completed:^{
		NSLog(@"Fetched all messages.");
	}];
```

That will login, then fetch messages, then for each message fetched, fetch the full message, log each full message and then log when it's all done.

## Bindings
Bindings let you use RAC to drive your user interface. See the [Mac sample project](https://github.com/github/ReactiveCocoa/tree/master/GHAPIDemo/GHAPIDemo).

But iOS doesn't have bindings. Thankfully, RAC's KVO wrapping makes it easy to bind to KVC-compliant properties a RAC subscribable. It looks like this:

``` obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.someLabel.text) to:RACAbleSelf(self.someText)];
```

The real beauty of this is that we could also use any RAC operations on the subscribable to which it is bound. For example, to transform the new value before propagating it to the bound object:

``` obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.someLabel.text) to:[RACAbleSelf(self.someText) select:^(NSString *newText) {
	return [newText uppercaseString];
}]];
```

Unfortunately, a lot of UIKit classes don't expose KVO-compliant properties. `UITextField`'s `text` property, for example, isn't KVO-compliant. For cases like that, we added `-[UIControl rac_subscribableForControlEvents:]` which sends a new value every time the control events fire.

To go even one step further, we wrapped that in a property on `UITextField` so you can just use `-[UITextField rac_textSubscribable]` to watch for changes to `text`. Now we can write:

```obj-c
[self rac_bind:RAC_KEYPATH_SELF(self.username) to:self.usernameField.rac_textSubscribable];
```

Our `username` property is now bound to the value of our `usernameField` text field.

See the [iOS sample project](https://github.com/github/ReactiveCocoa/tree/master/RACiOSDemo) for an example.

## Lifetime
The point of RAC is to make your life better as a programmer. To that end, `RACSubscribable`'s lifetime is a little funny.

RAC will keep subscribables alive for as long as they need in order to deliver events to its subscribers. This means you usually don't need to worry about keeping a strong reference to a subscribable. RAC will manage it for you.

RAC cleans up a subscribable when:

1. The subscribable sends an error or is completed, or
1. When all its subscribers have unsubscribed and it receives no new subscribers after one runloop iteration.

If you want to keep a subscribable alive past either of those cases, you need to keep a strong reference to it. But you shouldn't usually need to do that.

### KVO
KVO is a special case when it comes to lifetime. Subscribables created from a KVO-compliant property are kept alive for the lifetime of the source object. As such, they never really 'complete.' Instead, when the source object is dealloc'd, the subscribable removes all its subscribers and gets released.

### Disposables
The `-[RACSubscribable subscribe:]` method returns a `RACDisposable`. That disposable encapsulates the tasks necessary to stop and clean up the subscription. You can call `-dispose` on a disposable to end your subscription manually. Typically you won't need to manually track or dispose of disposables. They're automatically called by RAC as part of the subscribable's lifecycle.

## It's ugly!
Beauty is in the eye of the beholder! We've played with a lot of different formatting styles to try to find one that's both concise and readable. The examples are in the style we currently use.

That said, it's also a matter of getting used to what a different kind of code looks like. Give it time. It might grow on you.

## License
Simplified BSD License
{'fraction_non_alphanumeric': 0.08135100780824406, 'fraction_numerical': 0.002300102899340234, 'mean_word_length': 4.811466760464298, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2381985', 'n_tokens_mistral': 4948, 'n_tokens_neox': 4485, 'n_words': 2205}