基于RxJava的搜索框关键词匹配的demo代码
时间: 2024-01-24 09:02:29 浏览: 110
简易搜索框demo
下面是一个基于RxJava实现搜索框关键词匹配的demo代码,它可以实现在输入关键词时实时显示匹配的结果:
```java
public class SearchActivity extends AppCompatActivity {
private EditText etSearch;
private RecyclerView rvResult;
private SearchAdapter adapter;
private List<String> dataList = new ArrayList<>();
private Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
etSearch = findViewById(R.id.et_search);
rvResult = findViewById(R.id.rv_result);
adapter = new SearchAdapter(this, dataList);
rvResult.setLayoutManager(new LinearLayoutManager(this));
rvResult.setAdapter(adapter);
subscription = RxTextView.textChanges(etSearch)
.debounce(500, TimeUnit.MILLISECONDS)
.map(CharSequence::toString)
.observeOn(Schedulers.io())
.flatMap(this::search)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateResult);
}
private Observable<List<String>> search(String keyword) {
return Observable.create(subscriber -> {
List<String> result = new ArrayList<>();
// 模拟搜索过程
for (int i = 0; i < 10; i++) {
if (String.valueOf(i).contains(keyword)) {
result.add(String.valueOf(i));
}
}
subscriber.onNext(result);
subscriber.onCompleted();
});
}
private void updateResult(List<String> result) {
dataList.clear();
dataList.addAll(result);
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
```
这个demo中使用了RxTextView来监听EditText的文本变化,然后通过debounce操作符来限制搜索频率,避免频繁地进行搜索。接下来使用map操作符将CharSequence转换为String,然后在io线程中进行搜索,最后通过observeOn(AndroidSchedulers.mainThread())将结果回到主线程中进行更新。在search方法中,我们使用Observable.create方法来创建一个Observable对象,并在其中进行模拟搜索过程。最后在updateResult方法中更新搜索结果。
阅读全文