RxSwift - Debounce/Throttle “inverse”

梦想与她 提交于 2019-11-30 17:08:52

Updated for RxSwift 3 and improved throttle operator

With new behavior of throtlle operator, introduced in RxSwift 3.0.0-beta.1, you can use it just like that:

    downloadButton.rx.tap
    .throttle(3, latest: false, scheduler: MainScheduler.instance)
    .subscribe(onNext: { _ in
        NSLog("tap")
    }).addDisposableTo(bag)

Old version of answer

Use window operator and then transform Observable<Observable<Type>> to flat Observable using flatMap.

This sample code prints 'tap' only for first tap in every 3 seconds windows (or if tap count exceeds 10000).

    downloadButton.rx_tap
    .window(timeSpan: 3, count: 10000, scheduler: MainScheduler.instance)
    .flatMap({ observable -> Observable<Void> in
        return observable.take(1)
    })
    .subscribeNext { _ in
        NSLog("tap")
    }.addDisposableTo(bag)

Window is a great solution, but I find the sample operator more intuitive and also with correct behavior.

messagesHandler.messages
               .sample(Observable<Int>.timer(0.0, period: 2.0, scheduler: MainScheduler.instance))
               .subscribeNext { [weak self] message in
                    self?.playMessageArrivedSound()
               }.addDisposableTo(self.disposeBag)

The throttle operation does not do what I thought it should.

For people that also find throttle is too confusing:

"throttle will only forward an event once the source observable has stopped sending events for the specified period of time. This does not work well with regular event delivery" for more details.

In this case, the filter you want is

sample(Observable<Int>.timer(0.0, period: 2.0, scheduler: MainScheduler.instance))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!