Sobes.tech
Middle

Como adicionar suporte ao retorno de tipos RxJava no Retrofit?

sobes.tech IA

Resposta da IA

Adicionar a dependência converter-rxjava2 (ou converter-rxjava3 para RxJava 3) no build.gradle:

implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0' // ou adapter-rxjava3 para RxJava 3

Ao criar uma instância do Retrofit, adicionar RxJava2CallAdapterFactory (ou RxJava3CallAdapterFactory):

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create()) // Ou outro conversor
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // Ou RxJava3CallAdapterFactory
    .build();

Na interface Api Service, definir métodos que retornem tipos RxJava (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);
}