RamwiseMatt
RamwiseMatt

Reputation: 2957

RxSwift throttle() to get first element

I am looking for a way in which the throttle() operator gives up the first element in an Observable within a given time-interval, rather than the last element.

A similar question has been asked (and answered) in RxSwift - Debounce/Throttle "inverse", but there is an imperfection in those answers that I would like to avoid. That is, in an ideal scenario, the first element emitted in the Observable is obtained and any future ones are ignored for the duration of the time-interval. However, when working with window() or timer(), it is possible that two elements proceed within the given time-interval, because the timer happened not to run parallel to the start of the throttle() call. Example:

|..........|..........|..........|
                    ^   ^
                first   second

They fall into different windows and are therefore both accepted by the imperfect solution described in the linked answer.

Ideally, there would be a way to restart the timer as soon as the first element in a window comes in, so that the above example would instead look something like:

|..........|.......|..........|
                    ^   ^
                first   second (ignored)

Any ideas?

Edit: to be clear, I am not sure how the throttle() variety of RxSwift 3.0-beta1 handles this, but I am looking for a solution for RxSwift 2.x implementations.

Upvotes: 0

Views: 2276

Answers (1)

RamwiseMatt
RamwiseMatt

Reputation: 2957

As it turns out, rxSwift 3.0 deals with throttle() in exactly the way I desired. It takes an element and then ignores any further elements for x seconds (without having the 'window problem' I alluded to in the question).

For the sake of completeness: debounce() still works in accordance with rxSwift's 'old' definition of throttling. That is, it takes the last item in a time-interval.

Upvotes: 3

Related Questions