java实现debounce,RxJava运算符Debounce无法正常工作

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());

});

解决方案

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 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());

});

你可能感兴趣的:(java实现debounce)