yozhik
yozhik

Reputation: 5084

Retrotif2 + RxJava sending POST request failed

I want to send POST request with Retrofit + RxJava, but it is failing and I don't know the reason. In one activity it's working, in another - don't want to work:

private void sendMerchantInfo() {
        try {
            String advertiserOriginalDeepLink = "https://mywebsite.com/main-1?param1=value1&param2=value2";
                String urlGetParams = LinkParser.getUrlGETParams(advertiserOriginalDeepLink);

                Map<Object, Object> merchantInfo = LinkParser.parseUrlGetParams(urlGetParams);
                String merchantInfoJson = new Gson().toJson(merchantInfo); //{"param1":"value1","param2":"value2"}

                String url = "https://api.endpoint.com/v1/system/merchant/process";
                userService = this.serviceGenerator.createService(UserService.class, true);
                final Observable observable = userService.sendUserInfo(
                        url, new RetrofitMapBody(merchantInfo))
                        .doOnNext(new Consumer<ResponseBody>() {
                            @Override
                            public void accept(ResponseBody responseBody) throws Exception {
                                //handle 200 OK.
                            }
                        })
                        .onErrorResumeNext((ObservableSource<? extends ResponseBody>) v ->
                                Crashlytics.log("Send user info attempt failed."))
                        .subscribeOn(Schedulers.from(threadExecutor))
                        .observeOn(postExecutionThread.getScheduler());
                addDisposable(observable.subscribe());
            }
        } catch (Exception exception) {
            Crashlytics.log("Send user info attempt failed. " + exception.getMessage());
        }
    }

I suspect that problem in this part, I am trying to send request in OnCreate() method:

.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler());

Tried to use this, but no effect:

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());

What I am doing wrong? It always call onErrorResumeNext() It's probably something with threads because one time I got exception: networkonmainthreadexception. Please help.

Upvotes: 0

Views: 126

Answers (1)

Muhammad Youssef
Muhammad Youssef

Reputation: 373

Try using RxJava2 Adapter, it will save you a lot!

Step 1: Retrofit client setup

   private Retrofit getRetrofitClient() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //option 1
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.newThread())) //option 2
                .build();
    }

Step 2: APIService interface (Example)

@GET("endpoint")
Single<ResponseModel> fetch();

Step 3: Usage

  Single<ResponseModel> fetch() {
        return getRetrofitClient()
                    .create(APIService.class)
                    .fetch();
    }
  • Any non-2xx HTTP response will be wrapped in HttpException from which you can extract the status code, the status message and the full HTTP response.

  • Any connection errors will be wrapped in IOException

And that is all you need to do to wrap your network call in any RxJava stream.

Upvotes: 2

Related Questions