Android,RXJava,使用debounce搜索

时间:2016-10-04 06:05:11

标签: android rx-java rx-android

我使用debounce()来处理用户搜索并处理它在输入时暂停(在最后一个字符后1秒搜索):

RxSearchView.queryTextChanges(searchView)
            .debounce(1, TimeUnit.SECONDS)
            .subscribe(new Action1<CharSequence>() {
                @Override
                public void call(CharSequence charSequence) {
                    presenter.loadUsers(charSequence.toString());
                }
            });

所以如果用户删除所有字符,它等待1秒然后加载列表,我该如何处理它并立即加载列表?

2 个答案:

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