带有okhttp的Android

带有okhttp的Android

本文介绍了带有okhttp的Android rxjava-NetworkOnMainThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会遇到异常-android.os.NetworkOnMainThreadException,有时代码会起作用.

这是我的代码

Observable.create(new Observable.OnSubscribe<Response>() {
        OkHttpClient client = new OkHttpClient();

        @Override
        public void call(Subscriber<? super Response> subscriber) {
            try {
                Response response = client.newCall(request).execute();

                subscriber.onNext(response);
                subscriber.onCompleted();
            } catch (IOException e) {
                subscriber.onError(e);
            }

        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .unsubscribeOn(Schedulers.io())
            .map(new Func1<Response, Res>() {
                @Override

                public Res call(Response response) {

                    String post = new Scanner(response.body().byteStream(), "UTF-8")
                            .useDelimiter("\\A").next();
                    Log.d(TAG,post);
                    return model.deCryptData(post);
                }
            })

            .subscribe(new Action1<Res>() {
                @Override
                public void call(Res res) { ...

有时结果是:

我做错了什么?还是错误?

推荐答案

.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())

订阅新线程并在mainThread上观察

subscribe on new thread and observe on mainThread

这篇关于带有okhttp的Android rxjava-NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:08