Skip to content

Instantly share code, notes, and snippets.

@erica
Created July 11, 2020 03:57
Show Gist options
  • Save erica/e5cb2f08e49a25f340094f9c764d9f5d to your computer and use it in GitHub Desktop.
Save erica/e5cb2f08e49a25f340094f9c764d9f5d to your computer and use it in GitHub Desktop.
import Cocoa
import Combine
import ObjectiveC
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
enum Action {
static func run(after delay: Double, action: @escaping () -> Void) {
let delayTime = UInt64(delay * Double(NSEC_PER_SEC))
let dispatchTime = DispatchTime(uptimeNanoseconds: DispatchTime.now().rawValue + delayTime)
DispatchQueue.global(qos: .background)
.asyncAfter(deadline: dispatchTime, execute: action)
}
}
class AsyncRandomNumberSource {
var number: Int
var subject: PassthroughSubject<Int, Never>
func action() {
Action.run(after: Double.random(in: 0.1 ... 3.0)) { [weak self] in
if let self = self {
// send a number or end
switch Int.random(in: 1 ... 20) {
case 20:
self.subject.send(completion: .finished)
default:
self.number = Int.random(in: 1 ..< 1000)
self.subject.send(self.number)
self.roll()
}
}
}
}
func roll() {
action()
}
init(_ subject: PassthroughSubject<Int, Never>) {
self.subject = subject
number = 0
action()
}
}
let passthroughSubject = PassthroughSubject<Int,Never>()
let cancellableSubscriber = passthroughSubject.sink { completionInfo in
switch completionInfo {
case .finished: print("Done!!")
case .failure(let error): print("Error: \(error)")
}
} receiveValue: { stringElement in
print(stringElement, "received")
}
let source = AsyncRandomNumberSource(passthroughSubject)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment