I need some help with coroutines. I get that kotli...
# kotlin-native
o
I need some help with coroutines. I get that kotlin native only support coroutines on the main thread. But it should be possible to execute a background task (for example a http request) without blocking the ui right? I tried to create a simple task that uses the Dispatchers.Main but then the ui is blocked. Here is my code:
and the Android implementation...
a
ktor-client by default executes http requests on background thread. not on ui. only result of request transfered into coroutine to execute other code of coroutine on ui thread
if you want just http requests - use ktor-client and all will be good
if you want do some expensive work - you can use https://github.com/Autodesk/coroutineworker but you should pay attention to Kotlin/Native concurrency limitations. see https://github.com/Autodesk/coroutineworker#coroutineworker-prefers-frozen-state
👍 1
also https://github.com/badoo/Reaktive also can change threads, but you have to write code for background tasks in the same way taking into account the limitations of Kotlin / Native
lambda & result also freeze just like in coroutineworker.
o
Thank you! Then I will stick to ktor until I need something else.
s
ktor-client uses URLSession on iOS which executes on a background thread and by default even delivers results on that background thread.
o
So if I execute a ktor request with
Copy code
val result = client.get("url")
, do I need to do anything to get the result back on the ui thread?
s
No. Ktor takes care of that for you.
👍 1
o
Do database calls with sqldelight work the same way? And how do I handle async read/write to local storage?
Like shared prefs
a
Also Reaktive has thread local subscriptions and threadLocal() operator, both allow to avoid freezes in K/N in some circumstances.
h
@Sam Where’s the documentation in ktor that says it executes http requests on a background thread for iOS. I can’t seem to find it
s
h
I’m aware in iOS, when the delegateQueue is set to nil, the framework automatically creates a serial background queue. I thought Ktor did something different, or at least did some configuration.