RxJava运算符Debounce无效

Tar*_*hyi 3 android rx-java retrofit 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());
            });
Run Code Online (Sandbox Code Playgroud)

Myk*_*lis 10

作为@BenP的评论说,你似乎是应用debounce到商家信息自动填充服务.此调用将返回一个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());
    });
Run Code Online (Sandbox Code Playgroud)