What’s the best way to get a singleton HttpClient?...
# ktor
j
What’s the best way to get a singleton HttpClient? Couldn’t figure out how to just put it inside an Object
a
You can define a top-level property that will refer to an HttpClient instance.
a
@Aleksei Tirman [JB] As a top level property, it won't create another instance ?? It will return the same instance??
a
It will return the same instance because as far as I know under the hood it’s a static class property which is assigned only once.
m
I use this approach:
Copy code
val attributeHttpClient = AttributeKey<HttpClient>("httpClient")

val Application.httpClient: HttpClient
    get() = attributes[attributeHttpClient]

val ApplicationCall.httpClient: HttpClient
    get() = this.application.httpClient
and inside your application module
Copy code
this.attributes.put(attributeHttpClient, /* create your default http client here */)
Which is basically the same as using
lateinit var
top level and initializing once inside the module, but I like it a little better as it restricts usage to have at least access to the
application
a
@ayodele but you may have problems if auto-reloading is enabled.
👍 1