Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active April 9, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/10432abe75d246f4b0dc3d9066f37287 to your computer and use it in GitHub Desktop.
Save jasdev/10432abe75d246f4b0dc3d9066f37287 to your computer and use it in GitHub Desktop.
`randomNumberPublisher` that fetches a random integer from random.org.
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