网上有很多基于rx.data 方法的,或者responseXXX的,不采用那些方法的原因是,那些方法不支持 statusCode 的错误判定,也就是说,如果statusCode 是404 这种错误的时候,onError 不会触发。但是 rx.json是可以触发的。为什么这么做,大家去看RxAlamofire的源代码,很好理解,不做赘述,此处只解决问题。
extension ObservableType {
public func mapObject<T: Codable>(type: T.Type) -> Observable<T> {
return map { data -> T in
guard let data = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) else {
throw NSError(
domain: "",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Could not decode object"]
)
}
return try JSONDecoder().decode(T.self, from: data)
}
}
public func mapArray<T: Codable>(type: T.Type) -> Observable<[T]> {
return map { data -> [T] in
guard let data = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) else {
throw NSError(
domain: "",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Could not decode object"]
)
}
return try JSONDecoder().decode([T].self, from: data)
}
}
}
以下是使用方法举例:
return SessionManager.default.rx.json(.put, "\(endpoint)customer/\(customerID)", parameters: customerBean.dictionary, encoding: JSONEncoding.default)
.observeOn(MainScheduler.instance)
.mapObject(type: CustomerBean.self)
网友评论