Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public func mapObject<T: Decodable>(type: T.Type) -> Observable<T> {
- return flatMap { data -> Observable<T> in
- let (_, json) = (data as? (HTTPURLResponse, Any))!
- guard let jsonData = try? JSONSerialization.data(withJSONObject: json) else {
- throw NSError(
- domain: "",
- code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Please validate JSON for \(String(describing: T.self)) struct"]
- )
- }
- guard let object = try? JSONDecoder().decode(T.self, from: jsonData) else {
- throw NSError(
- domain: "",
- code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Failed to decode Codable struct \(String(describing: T.self))"]
- )
- }
- return Observable.just(object)
- }
- }
- public func mapArray<T: Decodable>(type: T.Type) -> Observable<[T]> {
- return flatMap { data -> Observable<[T]> in
- let (_, json) = (data as? (HTTPURLResponse, Any))!
- guard let jsonData = try? JSONSerialization.data(withJSONObject: json) else {
- throw NSError(
- domain: "",
- code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Please validate JSON for \(String(describing: T.self)) struct"]
- )
- }
- guard let objects = try? JSONDecoder().decode([T].self, from: jsonData) else {
- throw NSError(
- domain: "",
- code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Failed to decode Codable struct \(String(describing: T.self))"]
- )
- }
- return Observable.just(objects)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement