RxJava 2 / Retrofit 2 - NetworkOnMainThreadException

随声附和 提交于 2019-11-30 22:00:41

Your network is running on main thread, you can solve it by adding observeOn(AndroidSchedulers.mainThread()) and subscribeOn(Schedulers.io()) to your observable.

The observeOn(...) means that the results are emmited on the specified thread - in this case the UI thread.

The subscribeOn(...) call is basically where the request is processed. If omitted the computation is done on current thread.

Alright let me try and explain this in plain English. When you use AndroidSchedulers.mainThread(), it wraps the current block in the main thread, its no different from any method in your activity. The main context does not allow execution of networks requests, hence why yours fail. To remedy this your flow of observable need to change to accommodate the execution.

To test this theory, change all AndroidSchedulers.mainThread() to Schedulers.io() , therefore you would of to comment out all call to ui processing , like toast messages and leave behind simple Log messages , try it and see what happens.

you need to refactor this section, because it calls on the main thread.

 if (throwable instanceof UnauthorizedException) {
                            return mRequestManager.getTokenObservable(AutoAtendimentoApplication.getContext()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                                    .doOnNext(response -> Log.i("NEXT", "OK")).doOnError(throwable1 -> Log.i("ONERROR", "NOT OK"));

Here is a theoretical solution, do not wrap the getToken in a observable, create a class where the getToken can be called independently , let it return an observable from which you can then subscribe and observe from. thats all really, currently you wrap the above in the main thread.I do not know how else to make this simpler }

the problem must be on your getToken. You do not need the observeOn and the subscribeOn:

    return mAuthAPIService.getToken(request)
        .map(response -> storeTokens(response, context));

Adding those lines genererate the error. I do think the only place you need to specify its in the final subscriber.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!