This is Understanding Combine, written by Matt Neuburg. Corrections and suggestions are greatly appreciated (you can comment here). So are donations; please consider keeping me going by funding this work at http://www.paypal.me/mattneub. Or buy my books: the current (and final) editions are iOS 15 Programming Fundamentals with Swift and Programming iOS 14. Thank you!
.throttle
(Publishers.Throttle) is like a simplified version of .buffer
; it is also closely related to .debounce
. You supply a time interval. The operator runs a repeating timer and maintains a buffer of values received. When the time interval starts, the buffer is empty. When the time interval ends, the operator chooses one value out of the buffer and publishes it, and empties the buffer. Thus, values are filtered in such a way as to prevent more than one of them arriving per time interval.
The parameters are (see .delay for more information about the first three):
for:
scheduler:
options:
latest:
true
, it is the most recent value. If false
, it is the oldest value.For example:
let pub = Timer.publish(every: 0.2, on: .main, in: .common).autoconnect()
.scan(0) {i,_ in i+1}
.throttle(for: 0.5, scheduler: DispatchQueue.main, latest: true)
The values produced are 1
, 4
, 7
, 10
, and so on.