RxJava and Retrofit2: NetworkOnMainThreadException

前端 未结 2 1982
后悔当初
后悔当初 2020-12-06 09:49

I realize that I am using subscribeOn()/observeOn() on the MainThread. What are the set of options I can pass into subscribeOn()? What are the set of options I can pass into

相关标签:
2条回答
  • 2020-12-06 10:36

    You should call Observable.unsubscribeOn(Schedulers.io()), retrofit will unsubscribe at the end of a http-request.

    In RxJavaCallAdapterFactory of retrofit-rxjava-adapter

    it actions like this.

    if (!subscriber.isUnsubscribed()) {
        subscriber.onCompleted();
    }
    

    But when subscriber is a SafeSubscriber, it'll call unsubscribe finally.

    I have this issue in my app.

    Full code:

    o.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io());
    
    0 讨论(0)
  • 2020-12-06 10:45

    Rewrite the last part of your code to:

    service.getOneTestRx()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<MyTest>() {
            @Override
            public void onCompleted() {
                Log.d(TAG, "[onCompleted] ");
            }
    
            @Override
            public void onError(Throwable t) {
                Log.d(TAG, "[onError] ");
                t.printStackTrace();
            }
    
            @Override
            public void onNext(MyTest m) {
                Log.d(TAG, "[onNext] " + m.toString());
            }
        });
    

    Important note from @akarnokd:

    Worth mentioning that one needs to chain the calls as here because Observable is not the builder pattern (where you modify the settings of an existing object)

    0 讨论(0)
提交回复
热议问题