https://kotlinlang.org logo
Title
m

Marc Knaup

06/12/2019, 12:26 AM
Let's start a thread on how to use Ktor
HttpClient
in a
Worker
(background thread) on native 🙂
👀 1
Workaround for https://github.com/JetBrains/kotlin-native/issues/3061 Use
TransferMode.UNSAFE
to move(!) the
HttpClient
instance to your
Worker
. Unless you create it directly within the worker in which case this is not necessary. In both cases it is stored in an
@ThreadLocal
variable.
worker.execute(TransferMode.UNSAFE, { HttpClient(Ios) }) { httpClient -> threadLocalHttpClient = httpClient }
Launch the coroutine for executing
HttpClient
calls inside your
Worker
.
GlobalScope.launch(Dispatchers.Unconfined) {
	// use HttpClient
}
Workaround for https://github.com/Kotlin/kotlinx-io/issues/53
body = TextContent(
	text = someJson,
	contentType = ContentType.Application.Json
)
->
body = ByteArrayContent(
	bytes = someJson.toUtf8(),
	contentType = ContentType.Application.Json
)
You cannot create a
HttpClient
instance on a non-main thread until this is fixed: https://github.com/ktorio/ktor/issues/1183 There may be more of such issue though.
NSURLSession
responds on the main thread and the coroutine continues on that thread due to
Unconfined
😞 Is there a better way of getting the coroutine execution back into the
Worker
rather than using
worker.execute(TransferMode.UNSAFE, …)
?
e

e5l

06/13/2019, 12:41 PM
It looks like that problem can be solved by moving constants(and it fixed in the ios support branch). The next big problem is unfrozen values in
atomicfu
primitives and it can't be solved on ktor side for now.
🤔 1