-
-
Save jasdev/10432abe75d246f4b0dc3d9066f37287 to your computer and use it in GitHub Desktop.
`randomNumberPublisher` that fetches a random integer from random.org.
This file contains 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 Combine | |
import Foundation | |
enum RandomDotOrgError: Error { /// (1) A sample error conformance we’ll lean on. | |
case failedRequest | |
} | |
func randomNumberPublisher() -> Publishers.TryMap<URLSession.DataTaskPublisher, Int> { | |
var components = URLComponents(string: "https://www.random.org/integers/")! | |
components.queryItems = ["num", "min", "col"].map { URLQueryItem(name: $0, value: "1") } + | |
[ | |
URLQueryItem(name: "max", value: "235866"), | |
URLQueryItem(name: "base", value: "10"), | |
URLQueryItem(name: "format", value: "plain"), | |
URLQueryItem(name: "rnd", value: "new") | |
] | |
return URLSession.shared | |
.dataTaskPublisher(for: components.url(relativeTo: nil)!) | |
.tryMap { data, _ in | |
let randomNumber = Int( | |
String( | |
decoding: data, | |
as: UTF8.self | |
) | |
.trimmingCharacters(in: .newlines) | |
) | |
if let randomNumber = randomNumber, | |
randomNumber.isMultiple(of: 2) { | |
return randomNumber /// (2) Everything up to this point is scaffolding to make a request | |
/// to random.org—from there, we make sure it parses as an `Int` and, for sake of example, is even. | |
} else { | |
throw RandomDotOrgError.failedRequest /// (3) To more frequently simulate an error, | |
/// we `throw` if `randomNumber` is odd. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment