当用户在
我在我的 fragment 中使用以下代码:
SearchView
小部件中输入时,应用程序应该在后台线程中进行 API 调用以从服务器获取搜索结果,并在 UI 线程中在 RecyclerView 中显示它们。我在我的 fragment 中使用以下代码:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_fragment, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
RxSearchView.queryTextChanges(searchView)
.debounce(400, TimeUnit.MILLISECONDS)
.map(CharSequence::toString)
.switchMap(query -> retrofitService.search(query))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Item>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e(LOG_TAG, "Error", e);
}
@Override
public void onNext(List<Item> items) {
// adapter.addItems(...)
}
});
}
但我却收到了一个异常:
java.lang.IllegalStateException: Must be called from the main thread. Was: Thread[RxIoScheduler-2,5,main]
at com.jakewharton.rxbinding.internal.Preconditions.checkUiThread(Preconditions.java:35)
at com.jakewharton.rxbinding.support.v7.widget.SearchViewQueryTextChangesOnSubscribe.call(SearchViewQueryTextChangesOnSubscribe.java:18)
at com.jakewharton.rxbinding.support.v7.widget.SearchViewQueryTextChangesOnSubscribe.call(SearchViewQueryTextChangesOnSubscribe.java:10)
...
当我删除.subscribeOn(Schedulers.io())
时,搜索API调用会在片段创建时触发,并且在SearchView
中没有输入查询时,我会得到异常。
retrofit2.adapter.rxjava.HttpException: HTTP 422
然后,当我输入搜索查询 retrofitService.search(query)
就不再被调用了。
.observeOn(Schedulers.io())
就不必要了。 - Bartek Lipinski