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

Mark Alvaro

12/15/2021, 12:59 AM
Hello there! A project I work on maintains multiple HTTP client-backed services for Java, JavaScript, Kotlin, and Swift that all basically do the same thing, so Ktor’s multiplatform support looks super attractive for reducing a lot of duplication and maintenance burdens. I made a simple service using Ktor that calls a GET method, and noticed my function needed to become a suspend function (or maybe wrap the call with
runBlocking
, but I doubt that’s a performant or even suggested approach, and it won’t work for JS or common). As far as working with the service using Kotlin goes, whether in my common, JVM, JS, or whatever source set, I had no issues. The problem I have is consuming the service from Java code of course adds the Continuation argument, which isn’t something I want to impose on consumers of these services. I’ve seen a few threads in this channel about this issue, but I’m still wondering if there is any documentation or examples on how to make consuming the suspend function from Java sources more friendly. I saw mention of transforming to Futures or RxJava Singles or some other equivalent type, which is totally fine, but I’m not sure where to look for examples on how to even achieve that. I also know I can create a JVM-specific implementation that uses
runBlocking
, but again I’m pretty sure that should be avoided. Am I correct that using
runBlocking
would actually be worse than making the service using a RestEasy blocking client, due to coroutines not wanting to be blocked? Or would the performance be similar to a traditional blocking client, and I’d just be giving up benefits from using coroutines? Any pointers or links to guides would be appreciated!
b

Bruno Medeiros

12/15/2021, 1:59 AM
I think you will need specific interfaces for each platform, that reuses most of the logic in the
commonMain
code
runBlocking
is completely fine if you’re designing a blocking API. Maybe you can provide 2 methods in your Java API, one that is a
requestAsync
and returns a future and another
request
that runs the same thing , but around a
runBlocking
m

Mark Alvaro

12/15/2021, 2:02 AM
Oh cool. I already figured out how to do exactly that, so that should work for me.
b

Bruno Medeiros

12/15/2021, 2:21 AM
you might want a
requestAsync
returning a
Promise
on the JS side as well, this should be possible in the
jsMain
side of things
3 Views