How does the Throttle publisher work in Swift Combine?
Asked Answered
B

1

6

I'm stuck with Throttle publisher. I don't understand the way it picks intervals. Debounce publisher is much easier to understand, it picks an interval after each published value and checks whether new values are posted during the interval or not. I've seen some Throttle examples even from Apple, but they are very very simple.

Let's say we have some upstream which produces values and we know when all the values were produced (input: [Time]). Throttle publisher consumes these values, throttles them and produces values at some other times (output: [Time]). Is there a way to write a function which produces the correct expected output?

func output<Time>(interval: Time, input: [Time]) -> [Time] {
  //
}

Btw, I believe latest parameter doesn't play any role while picking the interval, does it? I belive it just picks values from intervals provided.

Barton answered 17/7, 2020 at 1:58 Comment(1)
does this help: heckj.github.io/swiftui-notes/#reference-throttle?Elsewhere
L
5

Throttle can be a tricky beast to understand. The parameter latest does make a difference, depending on timing of future values received - it controls which (first or last) of those values received during the throttle timeout are propagated when it expires.

Throttle doesn't really start "engaging" in delaying or cancelling further values until at least one value is received. Once that happens, you can think of it as 'starting a timer'. Let's use an example throttle of 1 sec time duration. That first value that starts the throttle engaging is always passed through. It's values after that which are effected by the throttle.

When the throttle starts engaging, further values are propagated only after that duration of 1 sec has expired. If you have multiple values propagated during that "time out" window, the parameter 'latest' chooses which of those properties gets stored and propagated down the publishing chain when the throttle timer expires and resets for the next series of values. latest being true means give me the last value that propagated before the throttle timer expired.

The timeline charts at https://heckj.github.io/swiftui-notes/#reference-throttle give a bit of sense to this, although in practice I've not found a tremendous need myself for choosing between latest or not, although I suspect there's use cases where it's critical.

If you're looking for something that just "slows down" the flow but keeps all the values, this isn't what you want - it drops values to enable the throttle.

Lump answered 17/3, 2021 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.