Eric Yuan
Eric Yuan

Reputation: 3344

Set cache on Okhttp3 off the main thread

The Okhttp3 used the builder to create OkHttpClient, please see below sample code.

 final OkHttpClient.Builder builder = new OkHttpClient.Builder();
   // Install an HTTP cache in the application cache directory.
  File cacheDir = new File(application.getCacheDir(), "http");
  final Cache cache = new Cache(cacheDir, BuildConfig.OK_HTTP_CACHE_SIZE_IN_BYTES);
  builder.cache(cache);

I am using Dagger 2 to inject the OKHttpClient and it injects the code on main thread. once I turned the stricMode on, we got below:

StrictMode policy violation; ~duration=333 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=23 violation=2

Is there way to set the cache off the main thread using Dagger 2?

For you reference. I have checked Jake's U2020 project, it doesn't have the problem. Is there anything I missed.

Upvotes: 3

Views: 1126

Answers (1)

AllDayAmazing
AllDayAmazing

Reputation: 2383

What you are doing shouldn't cause an error from a timeout while building (it could be something about the file directory that is causing this error), but if you are still having issues you could lazily instantiate the object via a Provider possibly and do that off of the main thread when needed. Just a thought as usually these chain a ton

Upvotes: 0

Related Questions