Last active
July 1, 2021 13:14
-
-
Save ChrisLowe-Takor/846641f1d6206d821fbeb465d7ea49a2 to your computer and use it in GitHub Desktop.
RxSwift rate limiter
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 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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Observeable<E>
needs to be replaced byObserveable<Element>
now.