我想在执行Observable时显示ProgressBar:
Observable<T> observable;
Observer<T> observer;
...................
observable.doOnSubscribe(()->{showProgressBar();}
.finallyDo(()-> {hideProgressBar();})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
...................
protected void showProgressBar() {
if (mProgressBar != null)
mProgressBar.setVisibility(View.VISIBLE);
}
protected void hideProgressBar() {
if (mProgressBar != null)
mProgressBar.setVisibility(View.GONE);
}
但是我收到了这个错误:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
在mProgressBar.setVisibility(View.VISIBLE);
如何从showProgressBar()
运行doOnSubscribe()
?
答案 0 :(得分:4)
observable.subscribeOn(Schedulers.newThread())
.doOnSubscribe(()->{showProgressBar();}
.subscribeOn(AndroidSchedulers.mainThread())
.finallyDo(()-> {hideProgressBar();})
.observeOn(AndroidSchedulers.mainThread())
应该有效。副作用操作符在任何线程调用它时同步执行,因此只需向后工作。请参阅this gist和this discussion。