我使用debounce()
来处理用户搜索并处理它在输入时暂停(在最后一个字符后1秒搜索):
RxSearchView.queryTextChanges(searchView)
.debounce(1, TimeUnit.SECONDS)
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
presenter.loadUsers(charSequence.toString());
}
});
所以如果用户删除所有字符,它等待1秒然后加载列表,我该如何处理它并立即加载列表?
答案 0 :(得分:8)
在您的情况下,只需要具有不同参数的debounce
运算符:
public final <U> Observable<T> debounce(Func1<? super T, ? extends Observable<U>> debounceSelector)
使用它可以过滤,哪些事件可以延迟:
RxSearchView.queryTextChanges(searchView)
.debounce(new Func1<CharSequence, Observable<CharSequence>>() {
@Override
public Observable<CharSequence> call(CharSequence charSequence) {
if (charSequence.length() == 0) {
return Observable.empty();
} else {
return Observable.<CharSequence>empty().delay(1, TimeUnit.SECONDS);
}
}
})
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
Log.d(MainActivity.class.getSimpleName(), new Date().toGMTString() + " " + charSequence.length() + " :" + charSequence);
}
});
答案 1 :(得分:1)
最简单的形式是merge去抖动的observable手动触发器,如下所示:
RxSearchView.queryTextChanges(searchView)
.debounce(1, TimeUnit.SECONDS)
.mergeWith(Observable.just("")) // manually tigger onNext with empty search
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
presenter.loadUsers(charSequence.toString());
}
});