Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
`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