Netflix/RxJava — pull request #368 by benjchristensen (2013-09-10 20:03:56+00:00)
Title: Operators: Throttle and Debounce

This adds `throttleFirst`, `throttleLast` (alias of `sample`) and `debounce` (aliased with `throttleWithTimeout`).

This merges pull request https://github.com/Netflix/RxJava/pull/258.

Unfortunately the Rx `throttle` operator behavior is actually `debounce`, not `throttle`. This pull request tries to address that.

Here is a good place to get a description of `throttle` versus `debounce`: http://drupalmotion.com/article/debounce-and-throttle-visual-explanation

> Debounce: Think of it as "grouping multiple events in one". Imagine that you go home, enter in the elevator, doors are closing... and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on... probably delaying the departure several minutes.

> Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy.. you are polite enough to let people in for 10 secs, but once that delay passes, you must go!

Other links includes:

- http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
- http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/

I feel we need some kind of `throttle*` operator name as an alias to `debounce` to help people discover it, especially those coming from Rx.Net or RxJS. I'm not fond of `throttleWithTimeout` which is what I have it as right now. Perhaps `throttleViaDebounce` even though that doesn't actually make sense?

I do not want to use `throttle` because it's not actually the definition of `throttle`. To confirm this I have asked over a dozen server-side engineers what their definition of `throttle` is and their expectations of an operator is. It never matches the Rx definition and they are always surprised by the `debounce` behavior.

I have included `throttleLast` as an alias to `sample` so that as people start typing `throttle...` it prompts them for the different options and discoverability will be improved instead of knowing to go look for `sample`.

The `throttleFirst` operator is included as an efficient approach to throttling tht does not involve ticking time, intervals or buffering in any way. It simply allows an `onNext` value through if the last `onNext` event was greater than X time units ago. All others are discarded. This matches server-side throttling expectations and is limited overhead.

Questions:

1) Is there a better name for `throttleWithTimeout` as an alias to `debounce`?
2) Does the documentation sufficiently explain the different strategies?
3) If ambitious in your review, does anyone see concurrency bugs?