我使用debounce()
来处理用户搜索并处理它在输入时的暂停(在最后一个字符之后搜索1秒):
RxSearchView.queryTextChanges(searchView)
.debounce(1, TimeUnit.SECONDS)
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
presenter.loadUsers(charSequence.toString());
}
});
所以如果用户删除所有字符,它等待1秒然后加载列表,我如何处理它并立即加载列表?
在您的情况下,只需要具有不同参数的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);
}
});
最简单的形式是将未绑定的可观察对象与手动触发器合并,如下所示:
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());
}
});