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

hawklike

05/17/2022, 2:40 PM
Hi, I have my Ktor server. I use the Ktor client to connect to another API in the Ktor server. The documentation says:
After you finish working with the HTTP client, you need to free up the resources ... call
client.close()
Should I call the
close()
function in the Ktor server? And if so, where?
a

Aleksei Tirman [JB]

05/18/2022, 8:33 AM
Should your server live as long as a client?
The
close
method on a server destroys it.
h

hawklike

05/18/2022, 8:36 AM
The client should live as long as the server. But I wonder if there won't be any leaks and is safe to not call the
close
method? :)
a

Aleksei Tirman [JB]

05/18/2022, 8:37 AM
Close
on a server or client?
h

hawklike

05/18/2022, 8:37 AM
Client's
close
method. There is any server
close
method?
a

Aleksei Tirman [JB]

05/18/2022, 8:38 AM
Server has the
stop
method.
If you don’t close a client and your application continues working, there will be a leak.
h

hawklike

05/18/2022, 8:41 AM
So then, should I close the client after every client's call? My client is a singleton...
a

Aleksei Tirman [JB]

05/18/2022, 8:42 AM
You should close it after all calls made.
h

hawklike

05/18/2022, 8:44 AM
Not sure if I understand it right. If the server is nonstop running, there might be another call at any time.
a

Aleksei Tirman [JB]

05/18/2022, 8:45 AM
I’m talking about the client only.
h

hawklike

05/18/2022, 8:46 AM
Ok, I will close the client when all calls are done and reopen the client when needed again. Is this the right way?
a

Aleksei Tirman [JB]

05/18/2022, 8:49 AM
No. If a client should live as long as your application then you don’t need to close it at all. Also, you can close it in some event handler that is launched just before an application is destroyed.
💯 1
You can’t use a client instance after you close it.
h

hawklike

05/18/2022, 8:53 AM
Thank you. Please, I have the last question. Is there any callback called right before the application is shut down (in order to clear resources)?
I see it. Since 2.0.0 there are these events. https://ktor.io/docs/custom-plugins.html#handle-app-events
a

Aleksei Tirman [JB]

05/18/2022, 9:47 AM
I meant your application in general, not a Ktor server application.
👍 1
12 Views