1

I am not clear on where Refrofit adapter and API classes should be kept in Android? Should I use Application class or Singleton to keep the adapter? How about the API interface classes?

  RestAdapter myRestAdapter;   // where should I keep this guy?

 MyAPI mApi = myRestAdapter.create(MyAPI.class);  // and how about this guy?

I have a few different api like MyApi1, MyApi2, that get called inside fragments at different points in app.

Thanks

user3186731
  • 441
  • 2
  • 5
  • 10

2 Answers2

11

Both of these should be treated as singletons and only created once.

The RestAdapter holds the common request executor, shared HTTP client configuration, remote service info, etc. These should be shared for every API interface.

The API interfaces should also be singletons. They are thread safe and require a bit of initial processing when created (minimal, but non-zero).

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • Your answer is fine, but you did mentioned where is the best place to place them. Is it a good ideia to keep a singleton instance of the RestAdapter in the App? And to build() it in the onCreate() method? And how about the API interfaces? Should I instantiate them inside activities? I had the same doubts and I missed these kind of documentation. Best! – Hugo Nogueira Sep 12 '14 at 16:52
0

Retrofit 1.7 doesn't allow one to perform request-specific operations, specifically the RequestInterceptor. Because of this I'm using a map of Singletons where each API gets its own RestAdapter. This way I can control Headers and such that are specific to an API.

I also give consumers of my library the ability to create a local API+RestAdapter combo for one-off scenarios if the need arises.

Kevin
  • 1,829
  • 1
  • 21
  • 22