RxJava运算符Debounce无效

时间:2017-11-13 23:34:33

标签: android retrofit rx-java rx-java2 debounce

我想在Android应用程序中实现场所自动完成功能,为此我使用了Retrofit和RxJava。我想在用户输入内容后每2秒做一次响应。我试图使用debounce运算符,但它不起作用。它立即给我结果,没有任何停顿。

 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 个答案:

答案 0 :(得分:8)

正如@BenP在评论中所说,您似乎正在将debounce应用于Place Autocomplete服务。此调用将返回一个Observable,它在完成之前发出单个结果(或错误),此时debounce运算符将发出该唯一的项目。

您可能想要做的是用以下内容去除用户输入:

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