How would I use a Ktor `HttpClient` in a backgroun...
# kotlin-native
m
How would I use a Ktor
HttpClient
in a background thread on iOS? The client needs to always be owned by the `Worker`'s thread and be accessible to all executions inside that worker 🤔 I basically need state in a
Worker
.
I thought about using an
@ThreadLocal
variable for that. But the documentation isn't very assuring on that:
PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
o
Yes, if you indeed want to attach state to given worker - @ThreadLocal is OK. In many other cases - maybe KTor on the main thread or frozen one could be OK.
m
Thank you. I'll go with
@ThreadLocal
for now.
HttpClient
cannot be frozen as it has mutable state internally. Using the main thread negatively affects my performance already in the iOS app and I want to get away from that.
I can't pass a newly created Ktor
HttpClient
instance to a worker.
Illegal transfer state 🤯
Debugging illegal state transfers is hardcore… https://github.com/JetBrains/kotlin-native/issues/3061
o
as I suggested in the bug, in case above may make sense to transfer factory, not the created object. However, it could be bug/feature in K/N, to check - force GC run after
HttpClient
is created with https://github.com/JetBrains/kotlin-native/blob/b49b0be2a12f46e771c7f9e20cb543f6845e170c/runtime/src/main/kotlin/kotlin/native/internal/GC.kt#L29
m
Also illegal state transfer:
{ HttpClient(Ios).also { GC.collect() } }