-1

I am trying to learn Rxjava2. I am facing a problem i.e, NetworkOnMainThreadException during network call using okHttp. I have to use only okHttp libary.

This is my method where I have written the code of RxJava2 for calling Login API.

@Override
public void onServerLoginClick(LoginRequest.ServerLoginRequest serverLoginRequest) {
    HttpParamObject httpParamObject = ApiGenerator.onServerLogin(serverLoginRequest);
    Service service = ServiceFactory.getInstance(activity, AppConstants.TASKCODES.LOGIN);

    try {
        Observable.just(service.getData(httpParamObject))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((Consumer<? super Object>) getObserver());
    } catch (JSONException | IOException | RestException | SQLException e) {
        e.printStackTrace();
    }
}

private Subscriber<LoginResponse> getObserver(){
    return new Subscriber<LoginResponse>() {
        @Override
        public void onSubscribe(Subscription s) {

        }

        @Override
        public void onNext(LoginResponse loginResponse) {
            getUiView().showToast(loginResponse.getMessage());
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };

}

Am I doing something wrong or missing anything? Please help me.

  • @ADM problem with integrating OkHttp Library with Rxjava2. No problem in the code of OkHttp. – Kartikeya Garg Dec 20 '17 at 07:38
  • Ok. Check [This](https://stackoverflow.com/questions/43488683/android-rxjava-with-okhttp-networkonmainthreadexception) if you haven't already . – ADM Dec 20 '17 at 07:42
  • Possible duplicate of [OkHttp Library - NetworkOnMainThreadException on simple post](https://stackoverflow.com/questions/28135338/okhttp-library-networkonmainthreadexception-on-simple-post) – F0XS Dec 20 '17 at 07:50

2 Answers2

2

You're calling service.getData(httpParamObject) in the main thread and passing that result to Observable.just. So your subscribeOn has no effect.

Check the documentation of Observable.create and use it instead of Observable.just

Alberto S.
  • 7,409
  • 6
  • 27
  • 46
-2

just remove Observable.just() as follows

  service.getData(httpParamObject)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((Consumer<? super Object>) getObserver());
Anbarasu Chinna
  • 975
  • 9
  • 28