enable response handlers to infer the handler result type
Closed this issue · 1 comments
angelodipaolo commented
Currently the ServiceTask
API uses Any?
to pass handler result values but this requires the updateUI handler to conditionally cast the Any?
type to the actual type of the expected value which is a bit of a burden. Ideally the handler should be able to infer the result type from the context.
A new API could enable custom handlers like:
extension ServiceTask {
func responseAs<T where T: ModelDecodable>(handler: ([T]) -> Void) -> ModelTask<[T]> {
return responseJSON { (json, response) -> [T]? in
guard let json = self.jsonObject(json, forKey: "brews"),
let jsonArray = json as? [AnyObject],
let decodedArray = ModelDecoder<T>.decodeArray(jsonArray) else {
throw ServiceTaskDecodeError.FailedToDecodeJSONArray
}
return decodedArray
}.updateUI { (brews: [T]?) in
guard let brews = brews else { return }
handler(brews)
}
}
}
That could enable your code to make service calls like:
brewClient
.fetchAllBrews()
.responseAs { [weak self] brews in
// self?.brews is of type `[Brew]?` and the type is inferred, no need to cast
self?.brews = brews
}
.error { error in
print("I AM ERROR = \(error)")
}
.resume()
nonsensery commented
Maybe these new methods could also do away with the ServiceTaskResult, as described in #33, since they're both breaking changes.