Hey, I have an interesting challenge. I want to wr...
# ktor
t
Hey, I have an interesting challenge. I want to write a single-use web server. That is: create a Kotlin function that launches an embedded server, waits for a request and returns data from that request after stopping the server. The problem is blocking the function (the one that does embeddedServer) return until the request comes in, since routed
get
is deep in the DSL. I wonder what primitives you would suggest me to use to do the blocking.
r
As a general solution for these kind of tasks you can create a
CompletableDeferred
beforehand, then start an asynchronous process passing it in and then immediately start waiting on it. The asynchronous process can then complete passed
CompletableDeferred
either normally with a result (or
Unit
if no result is needed) or exceptionally, which would automatically resume waiting coroutine. As for the Ktor, I recall there is a
Boolean
parameter on
start
method which allow it to suspend until server is not stopped, which should specifically do what you need.
t
Thank you, that sounds like something similar to the CountdownLatch hack in Java, but better :)
Yay for the wait argument, I read it, understood it, but didn't think of it this way. I still need to pass a value out of the
get
route though, but the blocking is nice. I'll play around.
In case you're curious this is what I came up with: https://github.com/TWiStErRob/disqus-spam-remover/blob/master/disqus-auth/src/main/kotlin/net/twisterob/disqus/auth/DisqusAuthenticator.kt#L74-L98
CompletableDeferred
definitely gives really nice control to me over the flow.
r
I actually did something similar while building authentication with Google, it's more or less straightforward way to do this kind of stuff :)