22

In ReactiveCocoa, what's the difference between the subscribeError: method vs. catch:? Why would you want to return a signal in catch:?

Ash Furrow
  • 12,341
  • 3
  • 54
  • 91

1 Answers1

32

-subscribeError: actually subscribes: this is the end of the line. Whereas -catch: simply transforms a signal into a new signal (and doesn't actually subscribe). Think of the signal like a program. When you -subscribeError:, you are telling the computer "I want to run this program, but I only want to hear back from you if it errors out." When you -catch:, you are saying "I've got this program that may throw an error, and I want to make a new one based on the old one that handles that error differently."

The reason you have to return a signal in -catch: is that it is not simply for squelching errors: it is actually for responding to errors. Once the original signal has errored out, it's as good as gone: if you want the resultant signal to keep going after a failure, you have to do give a new signal in -catch:.

Examples of what you could do in -catch::

  1. Return [RACSignal empty] if you want to fail silently and not throw an error.
  2. Return [RACSignal error:err] if you want to rethrow the error after doing something, or perhaps you want to transform the error.
  3. Return some other signal that you want to subscribe to in case the first one errors out.
Jonathan Sterling
  • 18,003
  • 12
  • 64
  • 79
  • Good explanation. launching an AlertView from within `-catch:` and returning an empty signal in order to "squelch" the error seems like a common point of entry for error handling with RAC, at least in my experience. – terry lewis Oct 18 '13 at 01:12
  • 2
    @terrylewis Be careful with threading there, however. Since a signal's values may be delivered on an arbitrary thread, your `-catch:` block may run there as well. – Justin Spahr-Summers Oct 18 '13 at 04:37