How to use throttle and debounce in RxSwift

Issue #426

throttle

https://rxmarbles.com/#throttle

throttle

Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.

1
.throttle(.milliseconds(500), scheduler: MainScheduler.instance)

In a time window, only the first item gets emitted.

💡 In other words, in a time window, take first and discard following.

For example, when failure, we show error message but don’t want to show error messages consecutively. We can use throttle to discard consecutive errors.

1
2
3
viewModel.fetchBooksFail
.observeOn(MainScheduler.instance)
.throttle(.seconds(2), scheduler: MainScheduler.instance)

debounce

https://rxmarbles.com/#debounce

debounce

Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.

1
.debounce(.milliseconds(500), scheduler: MainScheduler.instance)

If an element is about to get emitted, wait for a time window to see if there are other elements emitted. If yes, start the waiting again.

💡 In other words, in a time window, wait and take last

For example, when receiving data, we may need to wait for the final data if there are many data events emitted consecutively

1
2
3
viewModel.fetchBooks
.filter({ !$0.isEmpty })
.debounce(.milliseconds(500), scheduler: MainScheduler.instance)

Comments