Retrofit

repository·trunk·Indexed 13 days ago

https://github.com/lysine-dev/retrofit

A type-safe HTTP client for Android and Java. Supports version 3.0.0 and requires Java 8+ or Android API 21+. Includes a variety of call adapters for RxJava 1.x, 2.x, 3.x, Guava ListenableFuture, Scala Future, and Java 8 CompletableFuture, as well as converters for Gson and Guava Optional.

Tokens
11.2K
Snippets
49
Records
73
Agent score
94%

What's inside Retrofit

  1. What is Response Type Keeper and why use it?

    trunk

    Response Type Keeper is an annotation processor that prevents R8/ProGuard from stripping away types used in Retrofit service method generic parameters.

    The Problem

    When using R8/ProGuard, if a returned type (e.g., User in Call<User>) is not explicitly referenced elsewhere in your code, the optimizer may remove the type and replace the return type with a wildcard (Call<?>). This causes Retrofit to fail at runtime because it cannot pass a wildcard to a converter.

    The Solution

    This module automatically scans Retrofit service methods and generates explicit -keep rules for all types found in generic parameter positions, ensuring they are preserved during the shrinking process.

  2. Use delegating converters for Optional types

    trunk

    Delegating converters do not convert bytes to objects themselves. Instead, they delegate the conversion to another converter and wrap the result in an Optional to handle potentially-null values. Use these when your API interface returns Optional<T> instead of T.

    Available delegating converters:

    • Guava Optional<T>: com.squareup.retrofit2:converter-guava
    • Java 8 Optional<T>: com.squareup.retrofit2:converter-java8
  3. Control threading for RxJava requests

    trunk

    By default, all reactive types execute requests synchronously. You can control the execution thread using one of the following three methods:

    1. Per-call control: Call .subscribeOn(Scheduler) on the specific reactive type returned by the service method.
    2. Async Factory: Use RxJavaCallAdapterFactory.createAsync() to use OkHttp's internal thread pool for requests.
    3. Default Scheduler: Use RxJavaCallAdapterFactory.createWithScheduler(Scheduler) to provide a default subscription Scheduler for all requests handled by that factory.
  4. How Retrofit works

    trunk

    Retrofit is a type-safe HTTP client that turns your HTTP API into a Java or Kotlin interface. You define an interface where each method represents an HTTP endpoint, using annotations to describe the request (e.g., @GET, @POST, @Path). Retrofit then generates the implementation of that interface at runtime, allowing you to make synchronous or asynchronous requests by calling the interface methods.

    public interface GitHubService {
      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);
    }
  5. Configure Moshi serialization with MoshiConverterFactory

    trunk

    The Moshi converter allows you to use a custom Moshi instance to control serialization behavior. You can either use the default instance by calling MoshiConverterFactory.create() without arguments, or pass a pre-configured Moshi instance to MoshiConverterFactory.create(moshi) to apply custom adapters or settings.

    // Using a custom Moshi instance
    Moshi moshi = new Moshi.Builder()
        .add(MyAdapter.FACTORY)
        .build();
    
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.example.com/")
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .build();
  6. Control Threading for RxJava2 Requests

    trunk

    By default, all reactive types execute requests synchronously. You can control the execution threading using one of the following three methods:

    1. Per-call control: Call .subscribeOn(Scheduler) on the reactive type returned by your service method.
    2. Asynchronous factory: Use RxJava2CallAdapterFactory.createAsync() to use OkHttp's internal thread pool.
    3. Default Scheduler: Use RxJava2CallAdapterFactory.createWithScheduler(Scheduler) to supply a default subscription Scheduler for all requests created by that factory.
    // Example of per-call control
    myService.getUser()
        .subscribeOn(Schedulers.io())
        .subscribe(user -> ...);
  7. Execute calls synchronously vs. asynchronously

    trunk

    Retrofit Call instances can be executed in two modes:

    • Synchronous: Blocking execution.
    • Asynchronous: Non-blocking execution using callbacks.

    Important Lifecycle Rules:

    • Each Call instance can only be used once.
    • To reuse a request, call .clone() on the Call instance to create a new one.

    Threading Behavior:

    • Android: Callbacks are executed on the main thread.
    • JVM: Callbacks are executed on the same thread that performed the HTTP request.