How do I integrate OkHttp to work properly with `T...
# coroutines
h
How do I integrate OkHttp to work properly with
ThreadLocal.asContextElement
? Currenlty I use retrofit with
CompletableFuture
futures and then using
async
extension function from jdr8 integration package. But the request itself is executed in OkHttp own thread pool and so my
ThreadLocal
is null there, since coroutine doesn't know about this thread.
For example if I just use
Call<T>
and then wrap blocking
get
into
async
it works as expected.
d
If the value is lost on a thread switch, I'm afraid it's the code calling into OkHttp's fault
And you'll have to find a workaround there
g
One possible solution: use blocking API of retrofit to run request on own thread, but such request becoming non-cancellable, so I don't recommend this solution. What is your use case tho
h
That's what I'm doing currently, but it's a hack.
Copy code
val serviceCode = async {           api.serviceCode().execute().body()!! 
}
val tracked = async { api.trackedObjects().execute().body()!! 
}
No specific use case, I just want to use Retrofit and Coroutines. Ideally without using special CallFactory and relying on jdk8
Future
and then turning it into
Deferred
.
g
Yes, this is a bad hack and I wouldn't recommend to use it
So why do you need Thread local in context for this use case? Future supported by retrofit java8 adapter
Also no need to convert Future to Deferred, you can just use java8 coroutines adapter that provides
CompletableFuture.await()
extension function
Also, I see that you actually use Call<T> as return type, if so, you also don't need any converters to Deferred or change it to Future, you can use this library that provides coroutines adapter for retrofit2.Call
h
Judging by the code in
CallAwait
I will have the same problem, because it calls
enqueue
on OkHttp threadpool. I put user authentication in coroutinecontext to make requests to other services(ktor server) so it can be accessed inside an Interceptor that put's it into header for each request that's executed in said context.