场景:

用户输入搜索内容,进行输入框的变化监听,提供联想词。

需求:

避免频繁请求,限制时间内获取用户最后想搜索的内容

方案1:Handler实现 

利用postDelayed方法和可撤销的removeCallbacks方法实现

private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (EDIT_OK == msg.what) {
                String newText = etSearch.getText().toString();
                if(!TextUtils.isEmpty(newText)) {
                    setInputtipsQuery(newText);
                }
            }
        }
    };

private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(EDIT_OK);
        }
    };

etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mHandler.removeCallbacks(mRunnable);
                //600毫秒没有输入认为输入完毕
                mHandler.postDelayed(mRunnable, 600);
            }
        });

方案2:RxJava操作符进行限流

操作函数:debounce,500毫秒内采取最后一次的操作

subject.debounce(500,      TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<CharSequence>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable arg0) {

                    }

                    @Override
                    public void onNext(CharSequence charSequence) {
                        Log.d(TAG, "onNext" + charSequence.toString());
                        showSearchResult(charSequence);
                    }
                });


 

11-10 05:31