I'm trying to run a simple program that makes an H...
# coroutines
a
I'm trying to run a simple program that makes an HTTP call using retrofit but for some reason it is still running even after the call is finished and I can't figure out why It finishes after about a minute, but the call is done after a few seconds
Copy code
fun main() = runBlocking {
    val service = createFooService()
    val response = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        service.foo()
    }
    println(response)
}

interface FooService {
    @POST("foo")
    suspend fun foo(): FooResponse
}

dependencies {
    implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0")
    implementation("com.squareup.okhttp3:okhttp:4.10.0")
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.4")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
}
s
Did you have a typo in your example. Should it be
suspend fun main()
?
Also, no need to switch to IO dispatcher just before callin
suspend fun foo()
since it is already suspending, not blocking.
a
this is my last iteration I'm just trying different things if I do it like you say:
Copy code
suspend fun main() = runBlocking {
    val response = service.foo()
    println(response)
}
it's still the same thing I run it using
./gradlew run
if that changes anything
r
sounds like maybe some connection keepalive / resources that aren't being closed, keeping the application alive? I know that OkHttp uses its own thread pool, that should be closed for proper application shutdown
https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/#shutdown-isnt-necessary would explain why it shuts down after a minute, maybe a default connection keepalive of 60 seconds, after which the connection is terminated -> resources released -> application shutdown
s
Yeah... it could be a non-daemon thread by OkHttp kept alive (too long).
r
a
ok so now I have:
Copy code
suspend fun main() {
    val client = okHttpClient()
    val service = createFooService(client)
    val response = service.foo()
    println(response)
    client.dispatcher.executorService.shutdown()
    client.connectionPool.evictAll()
}
and it seems to work like expected! thanks for the help