RxJava operator Debounce is not working

[亡魂溺海] 提交于 2019-12-10 17:54:17

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/47275287/rxjava-operator-debounce-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!