Skip to content

Latest commit

 

History

History
54 lines (44 loc) · 2.27 KB

ReactiveExtensions.md

File metadata and controls

54 lines (44 loc) · 2.27 KB

ReactiveCocoa

Moya provides an optional ReactiveMoyaProvider subclass of MoyaProvider that does a few interesting things. Instead of calling the request() method and providing a callback closure to be executed when the request completes, we use RACSignals.

(Yeah, RACSignal, like the Objective-C ReactiveCocoa API. I'll get around to updating it to RAC 3 one of these days...)

The network request is not started until the signal is subscribed to. If a request is made while an identical request is already in-progress, the original signal is returned, instead. If the subscription to the signal is disposed of before the request completes, it is cancelled.

If the request completes normally, two things happen:

  1. The signal sends a value, a MoyaResponse instance.
  2. The signal completes.

If the request produces an error (typically a NSURLSession error), then it sends an error, instead. The error's code is the failing request's status code, if any, and the response data, if any.

The MoyaResponse class contains a statusCode, some data, and a(n optional) NSURLResponse. You can use these values however you like in subscribeNext or map calls.

To make things even awesomer, Moya provides some extensions to RACSignal that make dealing with MoyaResponses really easy.

  • filterStatusCodes() takes a range of status codes. If the response's status code is not within that range, an error is produced.
  • filterStatusCode() looks for a specific status code, and errors if it finds anything else.
  • filterSuccessfulStatusCodes() filters status codes that are in the 200-range.
  • filterSuccessfulStatusAndRedirectCodes() filters status codes that are in the 200-300 range.
  • mapImage() tries to map the response data to a UIImage instance and errors if unsuccessful.
  • mapJSON() tries to map the response data to a JSON object and errors if unsuccessful.
  • mapString() tries to map the response data to a string and errors if unsuccessful.

In the error cases, the error's domain is MoyaErrorDomain. The code is one of MoyaErrorCode's rawValues, where appropriate. Wherever possible, underlying errors are provided and the original response data is included in the NSError's userInfo dictionary using the "data" key.