Post

Replies

Boosts

Views

Activity

Correct loop for threaded UserDefaults.standard.addObserver observeValue
I am trying to write a Swift standalone library to monitor a UserDefaults value and callback a function in Python. To do so, I need an event loop in the Swift code that allows the Observer code to run and, when needed, call the callback function. I am monitoring the default via a KVO Observer class, which inherits a NSObject with UserDefaults.standard.addObserver in its init and implements observeValue as callback. To keep the loop running, up to now I called RunLoop.current.run() in the end of the Swift library invoked function. As you can imagine, this works well when the library is called from a main thread, which can provide inputs to the RunLoop. On the other hand, this fails (the library returns immediately) when the function is invoked from a secondary thread without e.g. the stdin attached. I am looking for an alternative to RunLoop.current.run() that: runs indefinitely can run in a secondary thread with no inputs does not block callbacks to observeValue I tried the most obvious choices like an infinite while or DispatchQueue but so far I was not able to achieve what I need. Further details about the issue can be found in a related StackOverflow question here: https://stackoverflow.com/questions/72982210/swift-and-python-get-a-runloop-that-can-run-in-threading Thanks in advance for your help.
6
1
1.3k
Jul ’22