Created
August 8, 2023 12:07
-
-
Save NoemiRozpara/0de3d8ff7bbd3f0ad90be165db5272fc to your computer and use it in GitHub Desktop.
Combine variable throttling time
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
// Originally found here: https://www.reddit.com/r/swift/comments/dvi5jj/dynamic_throttling_in_combine/?rdt=37713 | |
import Combine | |
import Foundation | |
class Example { | |
@Published var throttleInterval: DispatchQueue.SchedulerTimeType.Stride = 1 | |
@Published var valuesPublisher: Int = 0 | |
var cancellable: AnyCancellable? | |
var timerSendValues: Timer? | |
var timerChangeThrottle: Timer? | |
init() { | |
timerSendValues = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] timer in | |
guard let self else { return } | |
self.valuesPublisher += 1 | |
} | |
timerChangeThrottle = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { [weak self] timer in | |
guard let self else { return } | |
self.throttleInterval = self.throttleInterval == 1 ? 5 : 1 | |
} | |
cancellable = $throttleInterval | |
.removeDuplicates() | |
.map { [unowned self] seconds -> AnyPublisher<Int, Never> in | |
$valuesPublisher | |
.throttle( | |
for: seconds, | |
scheduler: DispatchQueue.main, | |
latest: true | |
) | |
.eraseToAnyPublisher() | |
} | |
.switchToLatest() | |
.sink { [unowned self] value in | |
print("Value: \(value) throttle interval: \(self.throttleInterval)") | |
} | |
} | |
} | |
let example = Example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment