Does Ktor’s `HttpClient` kick off it’s own corouti...
# ktor
k
Does Ktor’s
HttpClient
kick off it’s own coroutine to make requests? And do we have any control over that coroutineContext? I’m having trouble getting ktors HttpClient to behave nicely in regards to synchronization. Unless I wrap the
.get()
in
withContext(runTest.coroutineContext)
my tests do not wait for ktor request to return and the test will complete prematurely
a
The
HttpClient
implements
CoroutineScope
and has public
coroutineContext
property.
Copy code
HttpClient().coroutineContext
Could you please share the code for your test?
k
Yes it has coroutine context but it can not be changed.
Copy code
runTest {
            client.engine.coroutineContext = this.coroutineContext
            viewModel.getMain()
        }
Essentially without wrapping the HttpClient call in
withContext(someContext)
and setting
someContext
as TestScope.coroutineContext. The test will complete before HttpClient call returns. I’m having trouble acheiving synchronous mechanism without wrapping in
withContext
@Aleksei Tirman [JB]
a
Could you please share the definition of the
runTest
function? In what environment the
runTest
is executed?
p
@Ky If you use MockEngine, you could inject your test dispatcher.
Copy code
val engine = MockEngine.config {
    dispatcher = StandardTestDispatcher(testScheduler)

    addHandler {
        respondOk(resp)
    }
}

val http = HttpClient(engine)
// inject the http client into your code