`HttpClient` is to be treated as a lightweight eph...
# ktor
o
HttpClient
is to be treated as a lightweight ephemeral object. Instantiating `HttpClient`s should be done liberally.
HttpClient
itself is not resource heavy, all instances manage the underlying installed heavyweight engine in a manner consistent with the proper usage of that engine. Example:
OkHttp
engine forks a statically allocated base
OkHttpClient
by way of
newBuilder()
. Same goes for other engines. Is the above paragraph true? Assuming the clients are properly closed and all...
👀 1
m
That’s weird. I share
HttpClient
across my entire back-end as I’ve experienced them as being quite heavy 😅
o
@Marc Knaup I wanted to do the same, we are used to HttpClient-type objects being hungry. But due to the scarcity of Ktor documentation I dug a little deeper and the combination of searching this channel + actually seeing that the
OkHttp
engine forks an
OkHttpClient
led me to believe that Ktor's client is lightweight.
Copy code
private companion object {
    /**
     * It's an artificial prototype object 
     * to be used to create actual clients 
     * and eliminate the following issue:
     * <https://github.com/square/okhttp/issues/3372>.
     */
    val okHttpClientPrototype: OkHttpClient by lazy {
        OkHttpClient.Builder().build()
    }
}
I'll spam this every few days until it gets confirmed or debunked by somebody from Ktor 😅
m
Well it also depends on cleanup. If we have no lifecycle like we manage with
HttpClient
, when and how is cleanup performed, if at all?
r
I think it’s correct, the documentation is not very clear on this. But if you look at the documentation https://ktor.io/docs/request.html#sequential-requests and https://ktor.io/docs/client.html#close-client you can read that the client gets closed after a couple requests (even for single requests). When a client is closed you cannot use it anymore, so you will have to construct a new one. This does look like it is “light-weight”.