Ahmed na
05/21/2023, 2:22 AMCompanion
+ Coroutines
+ iOS
and callback functions
I'm trying to call a static function inside a callback,
print("Shared object: \(Greeting.Companion.shared)")
print("start as \(Greeting.Companion.shared.getCount())")
Greeting.Companion.shared.addCount()
Greeting.Companion.shared.onCallBack {
print("Shared object: callback \(Greeting.Companion.shared)")
print("Should be 1 and it is: \(Greeting.Companion.shared.getCount())")
}
the output is as follow
Shared object: com.example.testcompanion.Greeting.Companion@fcc011d0
start as 0
Shared object: callback com.example.testcompanion.Greeting.Companion@fd401110
Should be 1 and it is: 0
onCallBack
starts a coroutine then run the block of code provided ,
The issue is Companion object has changed and ofc all it's private members
I've created a sample project ,
Any Idea to solve this / workaround , or should i report an issue ?russhwolf
05/21/2023, 2:37 AM@ThreadLocal
annotation on your companion. That means that every thread gets a different version of the object. You're incrementing count from the calling thread but reading it on a thread from Dispatchers.Default
.
Remove that annotation. You shouldn't need it unless you're using the legacy memory manager.Ahmed na
05/21/2023, 2:42 AMrusshwolf
05/21/2023, 2:47 AM