Android:NetworkOnMainThreadException使用Rx android和Retrofit

时间:2017-05-02 09:14:50

标签: android retrofit rx-android

当使用rx android和retrofit时,我在线程异常时遇到了网络。这是我的代码:

public Observable<PostVariablesModel> requestApiItem() {
        return getauthenticationtoken.getToken().flatMap(new Func1<String, Observable<PostVariablesModel>>() {

            public Observable<PostVariablesModel> call(String token) {
                return service.postdata(value1, value2, value3, token);
            }
        }).subscribeOn(Schedulers.io());
    }


    public void postdata() {
        requestApiItem()   //I think problem is here any idea?
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PostVariablesModel>() {
                    @Override
                    public void onCompleted() {
                        System.out.print("Complete");
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.print("Fail");
                    }

                    @Override
                    public void onNext(PostVariablesModel apiResult) {
                        System.out.print(apiResult.toString());
                    }
                });
    }

完成http调用后,我们是否必须取消订阅?有什么想法吗?

以下是例外情况。我在代码中的postdata方法的onError上得到了这个异常:

android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
                                                                      at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
                                                                      at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                                      at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                                      at okhttp3.Dns$1.lookup(Dns.java:39)
                                                                      at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:170)
                                                                      at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:136)
                                                                      at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:81)
                                                                      at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:171)
                                                                      at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
                                                                      at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
                                                                      at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                      at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                      at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                      at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                      at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:179)
                                                                      at okhttp3.RealCall.execute(RealCall.java:63)
                                                                      at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
                                                                      at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
                                                                      at rx.Subscriber.setProducer(Subscriber.java:211)
                                                                      at rx.Subscriber.setProducer(Subscriber.java:205)
                                                                      at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:152)
                                                                      at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:138)
                                                                      at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:50)
                                                                      at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
                                                                      at rx.Observable.unsafeSubscribe(Observable.java:8666)
                                                                      at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:250)
                                                                      at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:147)
                                                                      at rx.internal.operators.OperatorMap$MapSubscriber.onNext(OperatorMap.java:74)
                                                                      at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:227)
                                                                      at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107)
                                                                      at android.os.Handler.handleCallback(Handler.java:739)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:158)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:7231)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

2 个答案:

答案 0 :(得分:4)

 return getauthenticationtoken.getToken().subscribeOn(Schedulers.io());

但您也可以使用默认调度程序创建调用适配器,它可以是Schedulers.io()。

return new Retrofit.Builder()
          .addConverterFactory(SimpleXmlConverterFactory.create())      
          .baseUrl("http://thecatapi.com/")
          .addCallAdapterFactory(
              RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) // <---- !!!
          .build()

答案 1 :(得分:0)

试试这个

public Observable<PostVariablesModel> requestApiItem() {
        return getauthenticationtoken.getToken().flatMap(new Func1<String, Observable<PostVariablesModel>>() {

            public Observable<PostVariablesModel> call(String token) {
                return service.postdata(value1, value2, value3, token);
            }
        });
    }

 public void postdata() {
        requestApiItem()   //I think problem is here any idea?
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<PostVariablesModel>() {
                    @Override
                    public void onCompleted() {
                        System.out.print("Complete");
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.print("Fail");
                    }

                    @Override
                    public void onNext(PostVariablesModel apiResult) {
                        System.out.print(apiResult.toString());
                    }
                });
    }

修改 您可以像这样尝试requestApiItem()函数:

public Observable<PostVariablesModel> requestApiItem() {

return service.postdata(value1, value2, value3, token)
                .flatMap(new Func1<PostVariablesModel>() {
                    @Override
                    public Observable<? extends PostVariablesModel> call(PostVariablesModel yourModel) {
                        return Observable.just(yourModel);
                    }
                });
}

注意:您可以尝试上面的代码(将返回的数据更改为您的模型)。