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,
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With