Skip to content

Instantly share code, notes, and snippets.

@novinfard
Last active February 15, 2021 02:03
Show Gist options
  • Save novinfard/c3e990e7406b745ad7fe894464678005 to your computer and use it in GitHub Desktop.
Save novinfard/c3e990e7406b745ad7fe894464678005 to your computer and use it in GitHub Desktop.
[Networking with Combine and Codable] #Combine #URLSession #networking
var subscriptions = Set<AnyCancellable>()
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }
// With Error handling
URLSession.shared
.dataTaskPublisher(for: url)
.tryMap { data, response in
try JSONDecoder().decode(SampleData.self, from: data)
}
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Retrieved object: \(object)")
}).store(in: &subscriptions)
// Wihtout error handling
URLSession.shared
.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: SampleData.self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Retrieved object: \(object)")
}).store(in: &subscriptions)
// Sending the request one time and share the outcome to the two subscribers
let networkPublisher = URLSession.shared
.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: SampleData.self, decoder: JSONDecoder())
.multicast(subject: PassthroughSubject<SampleData, Error>())
networkPublisher
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Sink1 Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Sink1 Retrieved object \(object)")
})
.store(in: &subscriptions)
networkPublisher
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Sink2 Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Sink2 Retrieved object \(object)")
}).store(in: &subscriptions)
networkPublisher
.connect()
.store(in: &subscriptions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment