Hi, is is possible to create a `StateFlow<HttpC...
# ktor
l
Hi, is is possible to create a
StateFlow<HttpClient>
which returns/caches a client based on a
Flow<HttpClientConfig>
so the client is update/a new client is created when the config is updated, but at the same time the old clients are cleaned up automatically, for example by the GC? In our use case we need to configure all our http clients dynamically during app runtime and the configuration is a Flow which can change at any time.
a
Could you please tell me what problems do you have with implementation?
l
We are building a multiplatform mobile app, which is used by different customers but we only publish a single app. Therefore, all configuration, including HttpClient configuration, such as http proxy, authentication and User Agent must be done at runtime. We already ha a configuration manager in our app we want to use to also configure all HttpClients, however the manager itself uses a HttpClient to fetch the configuration. Currently it is not possible to use the config from the configuration manager in the http client config, because the http client config is created before we can initialize the configuration manager.
Also we can not configure hostnames for http proxies, because we initialize the HttpClients in android on the main thread and android tries to resolve the hostname immediately during configuration on the main thread, which results in an exception
If we could use flows to configure http clients, it would solve multiple problems. Flows support coroutines and therefore support configuring and creating HttpClients in an async way. Flows automatically propagate changes from upstream flows, which allow reconfiguring HttpClients on demand. Flows decouple producer and consumer. In our application example, all components that use HttpClients should not know how and when an HttpClient is configured or updated. They just want to use the latest configured client to da their request. The only open question is how to cleanup HttpClients after they have been recreated with new configuration and how to drain open connections and requests.
a
Doesn’t calling
HttpClient.close()
work for you to release an HTTP client that is no longer needed?
l
The problem is, knowing when a client is no longer needed.
a
The
HttpClient.close()
method does a graceful shutdown so open connections won’t be closed immediately.
l
the
close()
must be called by the flow, before a new Client is created and returned by the flow, but if someone just got the latest client reference from the flow, no new requests can be created, this is a race condition between the flow closing the client and client being used to make requests.