Middle
How to add RxJava return type support in Retrofit?
sobes.tech AI
Answer from AI
Add the dependency converter-rxjava2 (or converter-rxjava3 for RxJava 3) in build.gradle:
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0' // or adapter-rxjava3 for RxJava 3
When creating a Retrofit instance, add RxJava2CallAdapterFactory (or RxJava3CallAdapterFactory):
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create()) // Or another converter
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // Or RxJava3CallAdapterFactory
.build();
In the Api Service interface, define methods that return RxJava types (Observable, Single, Completable):
public interface ApiService {
@GET("users")
Observable<List<User>> getUsers();
@GET("users/{id}")
Single<User> getUserById(@Path("id") int userId);
@POST("users")
Completable createUser(@Body User user);
}