Rxjava: Must be called from main thread of process

Created on 14 Jun 2017  ·  4Comments  ·  Source: ReactiveX/RxJava

public static <T> ObservableTransformer<T, T> applySchedulers(final IView view) {
        return new ObservableTransformer<T, T>() {
            @Override
            public Observable<T> apply(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .doOnSubscribe(disposable -> {
                            view.showLoading();//显示进度条
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doAfterTerminate(() -> {
                            view.hideLoading();//隐藏进度条
                        }).compose(RxUtils.bindToLifecycle(view));
            }
        };
    }

外面调用

mModel.getEndCityModelList(new Gson().toJson(map)).compose(RxUtils.applySchedulers(mRootView)).map(new BaseEntity<>()).subscribe(new CommonDisposableObserver<>(new HttpOnNextListener<List<CityModel>>() {
            @Override
            public void onNext(List<CityModel> cityModels) {
                setLetter(cityModels);
                if (adapter == null) {
                    adapter = new SelectCityAdapter(cityModels);
                    mRootView.setAdapter(adapter);
                }
            }

            @Override
            public void onFail(int code, String msg) {
                checkCode(code, msg, mAppManager);
            }
        }));

总是报错Must be called from main thread of process,不知道哪里的问题

Question

All 4 comments

I can't understand what you are saying. Please translate your problem into English.

The OP was asking why the code would run into this IllegalStateException: Must be called from main thread of process.

I guess the problem was the view.showLoading(); was executed on io thread, so moving the doOnSubscribe call after the observeOn(AndroidSchedulers.mainThread()) would be the easiest fix.

Thanks @aaronhe42!

Looks like this question has been answered. If you have further input on the issue, don't hesitate to reopen this issue or post a new one.

Was this page helpful?
0 / 5 - 0 ratings