hey all, need help to understand this particular e...
# multiplatform
a
hey all, need help to understand this particular error message running KMP library on iOS. I am generally aware about memory models (see comments on screenshot) and it normally works. But in some cases, I could not really understand exactly when, I get crash because of this message. So do I get it right: it complains about accessing lambda/closure. I assume the complain comes from inside the async {} block (debug picture is ambiguous), means we are in main thread. The closure was created in the kotlin code before calling this method. Does it mean that closure has been created on Non-Main thread?
i
you need to freeze it
a
you either freeze the state or you do thread managment in the shared codebase
t
A closure it not special memory model wise, it will be created on the thread you are on. if it helps think of it as pseudo code
pointer({ })
if that makes sense (since you say you understand memory models in general that should help). Then this pointer (created on the thread you are on), is passed to the async method, which in the end causes it to be accessed from the main thread. Since you did not freeze it (the closure, i.e. the pointer and what it points to), an exception occurs.
a
Freeze what exactly? How do freeze a closure called like get(url) { } ? It is not possible to freeze from swift.
t
right I did not even notice you are writing Swift, one easy way of course would be to write this code in Kotlin instead. Somewhere you must be referring a Kotlin/native object
a
Thanks for all responses, this confirms my guesses. Still trying to figure out how it can be since I checked all calls being on main thread. One crazy idea is that because this was observed only when app goes back from "sleep mode" (this is iOS), may be the Main thread which is used after sleep is different main than before sleep. 😕
Ok I was able to reproduce the issue and it indeed confirmed in in the error case closure is created NOT in main thread. And hints how to add native concurrency (which includes freeze()) to KMP project dependencies? I want to freeze the closure but freeze() method is not found. :/
t
the problem is not in the closure per se, Swift lets you share closures across threads just fine. You can see on your stacktrace you are already on the main thread. I assume its
callback
that jumps back into K/N code but obviously it is guess work with the information presented (not helped by how vague K/N stacktraces are). So likely the problem is
callback
or whatever it calls is not frozen. indeed if you’d port this code to K/N instead of Swift freezing the closure would also freeze
callback
(or whatever it references), but since this object should come from K/N somewhere, you can call
freeze
on it there yourself before it is ever passed to Swift