Skip to content

Instantly share code, notes, and snippets.

@ChrisLowe-Takor
Last active July 1, 2021 13:14
Show Gist options
  • Save ChrisLowe-Takor/846641f1d6206d821fbeb465d7ea49a2 to your computer and use it in GitHub Desktop.
Save ChrisLowe-Takor/846641f1d6206d821fbeb465d7ea49a2 to your computer and use it in GitHub Desktop.
RxSwift rate limiter
import RxSwift
extension ObservableType {
func rateLimit(rate: NSTimeInterval) -> Observable<E> {
let scheduler = MainScheduler.sharedInstance
var lastEmit = NSDate()
return filter { _ in
return scheduler.now.timeIntervalSinceDate(lastEmit) > rate
}
.doOn(onNext: { _ in
lastEmit = scheduler.now
})
}
}
// Sample usage
locationManager.rx_didUpdateLocations.map {$0.first}.filter{$0 != nil}.map{$0!.coordinate}.shareReplay(1)
.rateLimit(10)
.subscribeNext { location in
// location once every 10 seconds at the maximum
})
@BucekJiri
Copy link

BucekJiri commented Jul 1, 2021

Observeable<E> needs to be replaced by Observeable<Element> now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment