Android Rxjava With Okhttp - Networkonmainthreadexception
I sometimes get exception - android.os.NetworkOnMainThreadException, sometimes code works. Here is my code Observable.create(new Observable.OnSubscribe() {
Solution 1:
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
subscribe on new thread and observe on mainThread
Solution 2:
Try to create ThreadPool by yourself and subscribe on it.
ExecutorService webRequestsExecutor = Executors.newFixedThreadPool(1);
//Other stuff
.subscribeOn(Schedulers.from(webRequestsExecutor))
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io())
Solution 3:
You can't do network call on main thread .So for network you should use worker thread for calling network call in background and after your work is done just get response and post your UI.
Solution 4:
Change Schedulers.io()
to Schedulers.newThread()
Solution 5:
private Call uploadImage(Callback callback){
OkHttpClientclient=newOkHttpClient();
RequestBodyformBody=newFormEncodingBuilder()
.add("param_1", "1234")
.add("param_2", "acv")
.build();
Requestrequest=newRequest.Builder()
.url(URL)
.post(formBody)
.build();
Callcall= client.newCall(request);
call.enqueue(callback);
return call;
}
uploadImage(newCallback() {
@OverridepublicvoidonResponse(final com.squareup.okhttp.Response response) {
final String responseStr;
try {
responseStr = response.body().string();
HomeActivity.this.runOnUiThread(newRunnable() {
publicvoidrun() {
//Update UI here
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@OverridepublicvoidonFailure(Request req, IOException exp) {
}
});
Post a Comment for "Android Rxjava With Okhttp - Networkonmainthreadexception"