如何在订阅开始时显示对话框?

时间:2016-05-06 10:46:02

标签: java android rx-java rx-android

我想在执行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()

1 个答案:

答案 0 :(得分:4)

observable.subscribeOn(Schedulers.newThread())
          .doOnSubscribe(()->{showProgressBar();}
          .subscribeOn(AndroidSchedulers.mainThread())
          .finallyDo(()-> {hideProgressBar();})        
          .observeOn(AndroidSchedulers.mainThread())

应该有效。副作用操作符在任何线程调用它时同步执行,因此只需向后工作。请参阅this gistthis discussion