Last active
February 3, 2022 12:22
-
-
Save SebastianBoldt/6b618dca13525d82fb5a2451ebb665ad to your computer and use it in GitHub Desktop.
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 UIKit | |
import _Concurrency | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
// 1. | |
struct URLPollingSequence: AsyncSequence, AsyncIteratorProtocol { | |
// 2. | |
typealias AsyncIterator = URLPollingSequence | |
typealias Element = Data? | |
private let url: URL | |
private let delay: Int | |
public var isActive: Bool = true | |
init(url: URL, delay: Int) { | |
self.url = url | |
self.delay = delay | |
} | |
mutating func next() async throws -> Element? { | |
// 3. | |
guard isActive else { | |
return nil | |
} | |
try await Task.sleep(nanoseconds: UInt64(delay) * 1_000_000_000) | |
// 4. | |
let data = try await fetchData() | |
return data | |
} | |
func makeAsyncIterator() -> URLPollingSequence { | |
return self | |
} | |
private func fetchData() async throws -> Data { | |
let (data, _) = try await URLSession.shared.data(from: url) | |
return data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment