Search code examples
swiftrx-swift

RxSwift .debounce, .throttle for pagination


I'm trying to implement pagination. Whenever the table view scrolls, I want the reactor to check if it reached the bottom. But binding reactor.action whenever tableView's didScroll happens seemed unnecessary.

So I thought it would be better to use an operator to limit binding the reactor.action. But I'm not sure which operator is more suitable between .debounce and .throttle in this case.

self.tableView.rx.didScroll
    .skip(1)
    .withLatestFrom(self.tableView.rx.contentOffset)
    .map { [weak self] in
        print("didScroll")
        
        return Reactor.Action.pagination(
            contentHeight: self?.tableView.contentSize.height ?? 0,
            contentOffsetY: $0.y,
            scrollViewHeight: UIScreen.main.bounds.height
        )
    }
    .bind(to: reactor.action)
    .disposed(by: disposeBag)

I've tried .debounce and .throttle in my code. But still I'm not sure which one is more suitable.


Solution

  • Personally, I always use the reachedBottom(offset:) method supplied in RxSwiftExt.

    That said, on to the answer to the question...

    • The debounce operator is for when the input is jittery and you want to wait until it settles down to read off the input.

    • The throttle operator is for when the input is constantly emitting and you want to slow the stream down to a manageable number.

    • You can also use throttle for when the output will always be the same value (e.g., ()) and you want to react immediately. In this case, you want to make sure to set latest to false.

    I'm assuming what you want here is to wait until the user stops scrolling and then check the y of the contentOffset (and I expect you already know which to use based on the descriptions above.)

    Use debounce in this case.