对于我的应用程序的搜索功能,我有一个热的可观察链,它执行以下操作。
- 接受用户输入字符串到
EditText
(aTextChangedEvent
) (onmainThread
) - 去抖 300 毫秒(在
computation
线程上) - 显示加载微调器 (
mainThread
) - 使用该字符串查询 SQL 数据库(此查询可能需要 100 毫秒到 2000 毫秒之间的任何时间)(打开
Schedulers.io()
) - 向用户显示结果 (
mainThread
)
因为第 3 步的长度变化很大,所以会出现竞争条件,即较新的搜索结果显示在较新的结果上(有时)。假设用户想要输入chicken
,但由于输入速度很奇怪,单词的第一部分在整个术语之前发出:
- 首先发送搜索
chick
,然后发送chicken
. - 说
chick
需要1500ms
执行,而chicken
需要300ms
执行。 - 这会导致
chick
搜索结果错误地显示搜索词chicken
。这是因为chicken
搜索首先完成(仅用了 300 毫秒),然后是chick
搜索(1500 毫秒)。
我该如何处理这种情况?
- 一旦用户通过 a 我不关心旧搜索触发新搜索
TextChangedEvent
,即使它仍在运行。有什么办法可以取消旧的搜索?
完整的可观察代码:
subscription = WidgetObservable.text(searchText)
.debounce(300, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
//do this on main thread because it's a UI element (cannot access a View from a background thread)
//get a String representing the new text entered in the EditText
.map(new Func1<OnTextChangeEvent, String>() {
@Override
public String call(OnTextChangeEvent onTextChangeEvent) {
return onTextChangeEvent.text().toString().trim();
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.doOnNext(new Action1<String>() {
@Override
public void call(String s) {
presenter.handleInput(s);
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io())
.filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String s) {
return s != null && s.length() >= 1 && !s.equals("");
}
}).doOnNext(new Action1<String>() {
@Override
public void call(String s) {
Timber.d("searching for string: '%s'", s);
}
})
//run SQL query and get a cursor for all the possible search results with the entered search term
.flatMap(new Func1<String, Observable<SearchBookmarkableAdapterViewModel>>() {
@Override
public Observable<SearchBookmarkableAdapterViewModel> call(String s) {
return presenter.getAdapterViewModelRx(s);
}
})
.subscribeOn(Schedulers.io())
//have the subscriber (the adapter) run on the main thread
.observeOn(AndroidSchedulers.mainThread())
//subscribe the adapter, which receives a stream containing a list of my search result objects and populates the view with them
.subscribe(new Subscriber<SearchBookmarkableAdapterViewModel>() {
@Override
public void onCompleted() {
Timber.v("Completed loading results");
}
@Override
public void onError(Throwable e) {
Timber.e(e, "Error loading results");
presenter.onNoResults();
//resubscribe so the observable keeps working.
subscribeSearchText();
}
@Override
public void onNext(SearchBookmarkableAdapterViewModel searchBookmarkableAdapterViewModel) {
Timber.v("Loading data with size: %d into adapter", searchBookmarkableAdapterViewModel.getSize());
adapter.loadDataIntoAdapter(searchBookmarkableAdapterViewModel);
final int resultCount = searchBookmarkableAdapterViewModel.getSize();
if (resultCount == 0)
presenter.onNoResults();
else
presenter.onResults();
}
});