Last Updated: February 25, 2016
· gavrix

RACSignal post-event side effect

Those of you using ReactiveCocoa and signals probably know about injecting side effects in signals pipelines using -doNext:, -doCompleted:, -doError:. Framework will execute block given to these methods and then propagate corresponding event forward.

Sometimes however, you want to insert side effect after event was propagated. Here's example: suppose you RACSignal sending error messages as some action being performed or nil when error message should be dismissed. You bind that message to some UILabel's text property:

RAC(self, someLabel.text) = errorMessagesSignal;

Now, you want to inject a piece of code adding fade animation every time that text changes. But you can't inject that as -doNext: side effect, because that way animation will be added to label's previous state and you won't see new text appeared.

Here's a trick to inject side effect after new text gets set to that label:

RAC(self, someLabel.text) = [errorMessageSignal flattenMap:^RACStream *(id value) {
    return [[RACSignal return:value] doCompleted:^ {
        <side effect here>

In this case new value coming from errorMessageSignal will be sent all the way through, get set to labels' text property and then side effect executed.