In Swift, when using Combine for network requests, it's often useful to mock network layers for testing purposes. This allows you to simulate network responses and behaviors without relying on actual network calls. Here's an example of how to achieve this:
import Combine
import Foundation
// Network service protocol
protocol NetworkService {
func fetchData() -> AnyPublisher
}
// Real network service implementation
class RealNetworkService: NetworkService {
func fetchData() -> AnyPublisher {
let url = URL(string: "https://api.example.com/data")!
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.eraseToAnyPublisher()
}
}
// Mock network service implementation
class MockNetworkService: NetworkService {
func fetchData() -> AnyPublisher {
let mockData = Data("{\"key\":\"value\"}".utf8)
return Just(mockData)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
// ViewModel using the NetworkService
class ViewModel: ObservableObject {
private var cancellables = Set()
private let networkService: NetworkService
@Published var data: String = ""
init(networkService: NetworkService) {
self.networkService = networkService
fetchData()
}
private func fetchData() {
networkService.fetchData()
.decode(type: [String: String].self, decoder: JSONDecoder())
.map { $0["key"] ?? "" }
.receive(on: RunLoop.main)
.sink(receiveCompletion: { completion in
// Handle completion
}, receiveValue: { [weak self] value in
self?.data = value
})
.store(in: &cancellables)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?