Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift throttle how to get only last value from stream

I'm learning RxSwift, what I would like achieve is to get mechanism which prints me text from UITextFied, but after given interval.

How it works now: when I type first character this character is immediately printed out (not after delay how I expected) and if I keep on typing long sentence, text is printed after each two second (as interval is set in throttle), but I would like to have only latest text value.

My code:

inputField.rx.text.orEmpty
        .throttle(2, latest: true, scheduler: MainScheduler.instance)
        .subscribe(onNext: { text in
            print("\(text)")
        }, onDisposed: nil)
        .addDisposableTo(disposeBag)

Im looking for your help Rx fellows :) Thanks

like image 964
Robert Avatar asked May 29 '17 19:05

Robert


1 Answers

Use debounce instead of throttle.

From the documentation for 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.

From the documentation for 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.

like image 130
Daniel T. Avatar answered Oct 26 '22 00:10

Daniel T.