Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST with RxJava 2 + Retrofit 2?

This question may sound like a no-brainer but I'm having a hardtime.

I can do the post with retrofit 2 this way:

class RetrofitClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

Api service interface:

 @POST("postsInit")
    @FormUrlEncoded
    Call<InitPost> postInit(
            @Field("appVersion") String versionName,
            @Field("appId") String applicationId,

    );

And finally:

apiService.postInit(versionName, applicationId).enqueue(new Callback<InitPost>() {
            @Override
            public void onResponse(@NonNull Call<InitPost> call, @NonNull Response<InitPost> response) {

                if (response.isSuccessful()) {
                    Timber.d("post submitted to API");
                    getInitResponse();
                }
            }

            @Override
            public void onFailure(@NonNull Call<InitPost> call, @NonNull Throwable t) {

                if (call.isCanceled()) {
                    Timber.e("Request was aborted");
                } else {
                    Timber.e("Unable to submit post to API.");
                }

            }
        });

How can I convert this to RxJava 2 ? I've already implemented the converter factory but there is no info on the internet for using rxJava 2 and retrofit 2 together.

like image 819
Ege Kuzubasioglu Avatar asked Jan 08 '18 09:01

Ege Kuzubasioglu


1 Answers

Converting your call in RxJava code:-

apiService.postInit(versionName, applicationId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .unsubscribeOn(Schedulers.io())
            .subscribe(new Subscriber<InitPost>() {
                @Override
                public void onSubscribe(Subscription s) {

                }

                @Override
                public void onNext(InitPost initPost) {

                }

                @Override
                public void onError(Throwable t) {

                }

                @Override
                public void onComplete() {

                }
            });
}

Post service interface:

@POST("postsInit")
@FormUrlEncoded
Observable<InitPost> postInit(
        @Field("appVersion") String versionName,
        @Field("appId") String applicationId,
);
like image 127
Paresh P. Avatar answered Oct 03 '22 23:10

Paresh P.