Last active
March 23, 2021 23:16
-
-
Save karenxpn/a509f77eebefa55563f7732824bc4e32 to your computer and use it in GitHub Desktop.
Our service to fetch server response and parse it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
import Alamofire | |
protocol ServiceProtocol { | |
func fetchChats() -> AnyPublisher<DataResponse<ChatListModel, NetworkError>, Never> | |
} | |
class Service { | |
static let shared: ServiceProtocol = Service() | |
private init() { } | |
} | |
extension Service: ServiceProtocol { | |
func fetchChats() -> AnyPublisher<DataResponse<ChatListModel, NetworkError>, Never> { | |
let url = URL(string: "Your_URL")! | |
return AF.request(url, | |
method: .get) | |
.validate() | |
.publishDecodable(type: ChatListModel.self) | |
.map { response in | |
response.mapError { error in | |
let backendError = response.data.flatMap { try? JSONDecoder().decode(BackendError.self, from: $0)} | |
return NetworkError(initialError: error, backendError: backendError) | |
} | |
} | |
.receive(on: DispatchQueue.main) | |
.eraseToAnyPublisher() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment