Skip to content

Instantly share code, notes, and snippets.

@Ravi61
Created August 18, 2019 15:54
Show Gist options
  • Save Ravi61/008a97f25bc36b51454d7333de16ac97 to your computer and use it in GitHub Desktop.
Save Ravi61/008a97f25bc36b51454d7333de16ac97 to your computer and use it in GitHub Desktop.
Lossy operations for backpressure
/// We'll create a random Int emitting infinite Observable and
/// apply out lossy operators on it
let X = Observable<Int>.create { observer -> Disposable in
while true {
let randomInt = UInt32.random(in: 1...3)
print("Waiting for \(randomInt) second(s) to produce \(randomInt)")
sleep(randomInt)
observer.onNext(Int(randomInt))
}
return Disposables.create()
}.share()
_ = X.subscribeOn(SerialDispatchQueueScheduler(qos: .background))
.debounce(.seconds(2), scheduler: MainScheduler.instance)
.subscribe(onNext: { value in
print("Debounced \(value)")
})
_ = X.throttle(.seconds(2), scheduler: MainScheduler.instance)
.subscribe(onNext: { value in
print("Throttled \(value)")
})
let aScheduler = SerialDispatchQueueScheduler(internalSerialQueueName: "backgroundQueue1")
let A = Observable.repeatElement("A", scheduler: aScheduler).throttle(.seconds(2), scheduler: aScheduler)
_ = A.sample(X)
.subscribe(onNext: { value in
print("Sampled \(value)")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment