Skip to content

Instantly share code, notes, and snippets.

@nthState
Last active August 15, 2022 12:17
Show Gist options
  • Save nthState/5f4ec484a378e17160904b144bf1c03e to your computer and use it in GitHub Desktop.
Save nthState/5f4ec484a378e17160904b144bf1c03e to your computer and use it in GitHub Desktop.
CombineVsAsyncAwait
struct Product: Decodable {
let title: String
}
class MyCombine {
func getWithCombine() -> AnyPublisher<Product, Error> {
let url = URL(string: "https://dummyjson.com/products/1")!
return URLSession.shared.dataTaskPublisher(for: url)
.map { result in
return result.data
}
.decode(type: Product.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
func useCombineMethod() {
cancellable = getWithCombine()
.sink { completion in
switch completion {
case .finished:
print("finished")
case .failure(let error):
print("set warning for: \(error)")
}
} receiveValue: { prd in
self.product = prd
}
}
}
struct MyAsync {
func fetchProduct() async throws -> Product {
let url = URL(string: "https://dummyjson.com/products/1")!
let request = URLRequest(url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let product = try JSONDecoder().decode(Product.self, from: data)
return product
}
func useProduct() async {
do {
let product = try await fetchProduct()
} catch let error {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment