【问题标题】:RxJava operator Debounce is not workingRxJava 运算符 Debounce 不起作用
【发布时间】:2018-04-26 18:46:12
【问题描述】:

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

【问题讨论】:

  • 看起来您正在消除网络调用的抖动。可能您应该反跳用户输入事件。

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


【解决方案1】:

正如@BenP 在评论中所说,您似乎正在将debounce 应用于Place Autocomplete 服务。此调用将返回一个 Observable,该 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());
    });

【讨论】:

  • @ViktorYakunin 此处的目的是防止在每次用户输入更改时进行自动完成网络调用。 Debounce 允许我们可靠地处理新的用户输入,但将其限制为每两秒最多一次调用(即使输入的变化比这更快)。 reactivex.io/documentation/operators/debounce.html
  • 为什么是 flatMap 而不是 switchMap?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
相关资源
最近更新 更多