https://kotlinlang.org logo
#ktor
Title
# ktor
j

João Gabriel Zó

10/13/2022, 12:28 PM
What’s the best way to get a singleton HttpClient? Couldn’t figure out how to just put it inside an Object
a

Aleksei Tirman [JB]

10/13/2022, 12:37 PM
You can define a top-level property that will refer to an HttpClient instance.
a

ayodele

10/13/2022, 1:06 PM
@Aleksei Tirman [JB] As a top level property, it won't create another instance ?? It will return the same instance??
a

Aleksei Tirman [JB]

10/13/2022, 1:12 PM
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

maxmello

10/13/2022, 1:12 PM
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

Aleksei Tirman [JB]

10/13/2022, 1:15 PM
@ayodele but you may have problems if auto-reloading is enabled.
👍 1
67 Views