One of my favorite patterns using Dagger is to lazily initialize my OkHttpClient on a background thread the first time a network call is made. Typically, the cost of initializing your OkHttpClient is paid at app start time and on the main thread. This cost is non-zero, particularly if your client is configured with a response Cache and/or CertificatePinner . If you’re using RxJava with Retrofit, lazily initializing your client on a background thread is a breeze. Let’s dive into how to do it!

Start by ensuring all your @Provides functions request a Lazy<OkHttpClient> instead of a raw instance. Lazy is a wrapper provided by Dagger that allows us to defer initialization of the wrapped type until Lazy.get() is called. Then hook up your OkHttpClient to your Retrofit instance using the callFactory API:

Request a lazy OkHttpClient instance and plug it into Retrofit

To ensure your client (and its dependencies such as Cache ) are initialized on a background thread, it’s helpful to check what thread you’re on when they’re allocated:

Check to ensure initialization isn’t taking place on the main thread.

Bingo, you’re done!

As with any optimization, measure before and after to see if lazy initialization off the main thread makes sense for your use case. Happy coding!

Attribution: this pattern wasn’t invented by me and was pioneered by Jake Wharton. Square has been using this pattern in their apps for a few years.