java - Should I use one global Retrofit instance or create one for each request in Android? -
well, lost in using retrofit now... @ first write singleton helper class hold service instance created retrofit instance. convenient service , make http request, find can't access token sharedpreferences, because helper instance static. because use authenticator interface deal authentication, not possible pass access token when making request. try extend application class , hold application instance in static field, android studio give me warning(do not place android context classes in static fields; memory leak (and breaks instant run)
).
so have choice: write static helper method that, each request, accepts access token, build retrofit instance, create service instance , make request. confusing whether best practice. what's difference between reusing 1 service instance , creating service each request?
ps: word service
above refers service instance created someretrofit.create(someserviceinterface.class)
, not android.app.service
.
i suggest go ahead singleton approach only,as design prospective .
if create multiple instance of service each 1 of them have different network properties readtimeout , writetimeout , response logging property , etc or have set them 1 single property , if our working in team give alot of headache.
and usercase faced , @ later point of time backend team on additional header param each request device os version have add property retrofit client pain .
here snippet of code , how handle headers .
public static retrofit getrestadapter(final hashmap<string, string> requestheadermap) { httplogginginterceptor interceptor = new httplogginginterceptor(); interceptor.setlevel(httplogginginterceptor.level.body); okhttpclient client = new okhttpclient.builder() .addinterceptor(interceptor) .addinterceptor(rewrite_cache_control_interceptor) .addnetworkinterceptor(new interceptor() { @override public response intercept(chain chain) throws ioexception { request.builder builder = chain.request().newbuilder(); set<map.entry<string, string>> entryset = requestheadermap.entryset(); (map.entry<string, string> entry : entryset) { if (entry.getvalue().isempty()) builder.removeheader(entry.getkey()); else builder.addheader(entry.getkey(), entry.getvalue()); } request request = builder.build(); return chain.proceed(request); } }).build(); return new retrofit.builder() .baseurl(constants.base_url) .client(client) .addconverterfactory(gsonconverterfactory.create()) .build(); }
and instance of requestheadermap global instance , data being pushed using observable pattern .
i hope take decision .
Comments
Post a Comment