Taras Stavnychyi
Taras Stavnychyi

Reputation: 975

RxJava operator Debounce is not working

I want to implement place autocomplete in Android application, and for this I'm using Retrofit and RxJava. I want to make response every 2 seconds after user type something. I'm trying to use debounce operator for this, but it's not working. It's giving me the result immediately without any pause.

 mAutocompleteSearchApi.get(input, "(cities)", API_KEY)
            .debounce(2, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(prediction -> Observable.fromIterable(prediction.getPredictions()))
            .subscribe(prediction -> {
                Log.e(TAG, "rxAutocomplete : " + prediction.getStructuredFormatting().getMainText());
            });

Upvotes: 3

Views: 6563

Answers (1)

Myk Willis
Myk Willis

Reputation: 12869

As @BenP says in the comment, you appear to be applying debounce to the Place Autocomplete service. This call will return an Observable that emits a single result (or error) before completing, at which point the debounce operator will emit that one and only item.

What you probably want to be doing is debouncing the user input with something like:

// Subject holding the most recent user input
BehaviorSubject<String> userInputSubject = BehaviorSubject.create();

// Handler that is notified when the user changes input
public void onTextChanged(String text) {
    userInputSubject.onNext(text);
}

// Subscription to monitor changes to user input, calling API at most every
// two seconds. (Remember to unsubscribe this subscription!)
userInputSubject
    .debounce(2, TimeUnit.SECONDS)
    .flatMap(input -> mAutocompleteSearchApi.get(input, "(cities)", API_KEY))
    .flatMap(prediction -> Observable.fromIterable(prediction.getPredictions()))
    .subscribe(prediction -> {
        Log.e(TAG, "rxAutocomplete : " + prediction.getStructuredFormatting().getMainText());
    });

Upvotes: 12

Related Questions