RxSwift - Debounce/Throttle “inverse”

前端 未结 2 1342
臣服心动
臣服心动 2021-01-03 21:10

Let\'s say I have an instant messaging app that plays a beep sound every time a message arrives. I want to debounce the beeps, but I\'d like to play the beep so

2条回答
  •  半阙折子戏
    2021-01-03 22:11

    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> 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 in
            return observable.take(1)
        })
        .subscribeNext { _ in
            NSLog("tap")
        }.addDisposableTo(bag)
    

提交回复
热议问题