问题描述
我正在尝试学习Rxjava2.我在使用okHttp进行网络通话时遇到了一个问题,即NetworkOnMainThreadException.我只需要使用okHttp库.
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.
这是我编写用于调用Login API的RxJava2代码的方法.
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.
推荐答案
您正在主线程中调用service.getData(httpParamObject)
,并将结果传递给Observable.just
.因此,您的subscribeOn
没有任何作用.
You're calling service.getData(httpParamObject)
in the main thread and passing that result to Observable.just
. So your subscribeOn
has no effect.
检查 Observable.create 的文档,并使用它代替Observable.just
Check the documentation of Observable.create and use it instead of Observable.just
这篇关于使用OkHttp和RxJava2的NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!