简体   繁体   中英

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.

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,
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM