NetworkingMidMCQ
What is Combine and how does it relate to networking?
Test your knowledge:
Explanation & Code
Answer:
Combine is Apple's reactive framework for processing asynchronous events over time. URLSession has a built-in Combine publisher, making it natural to chain networking, decoding, and UI updates.
Code Example:
import Combine
class ArticleService {
private var cancellables = Set<AnyCancellable>()
func fetchArticles() -> AnyPublisher<[Article], Error> {
let url = URL(string: "https://api.example.com/articles")!
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: [Article].self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
// In ViewModel
service.fetchArticles()
.sink(
receiveCompletion: { completion in
if case .failure(let error) = completion {
print("Error: \(error)")
}
},
receiveValue: { [weak self] articles in
self?.articles = articles
}
)
.store(in: &cancellables)
Note: async/await is now preferred for new code, but Combine is still widely used and worth knowing.
Rate your understanding: