Anybody explain me how to handle mutable singleton...
# kotlin-native
d
Anybody explain me how to handle mutable singletons in common module. Here is the changes that I add into kotlin-mpp-example: https://github.com/KamiSempai/kotlin-mpp-example/commit/35627af6d4d3e1e0b7824adb708e9e0906db4a3c I add a new one object Factory2 in common module that has lazy initialization of its properties. On android it works fine but in iOS i get InvalidMutabilityException. Ok, I know that in Kotlin Native all singletons are freezed and I should use annotation ThreadLocal to make it mutable atleast in one thread. BUT this is common module. I can't use anything from Kotlin Native. Does any practices that helps to solve such problems in common modules? Right now I only see that this immutability cut a lot of code which can be moved into common module.
o
lazy since 0.9 works on singletons
d
It seems I gave an unfortunate example. I meant that content of singleton will change during execution of program. Here I change the code. So my question should be clear: https://github.com/KamiSempai/kotlin-mpp-example/commit/0089fd49a66e7e20cc113f418fa38083ae02d856 In this case "by lazy" not helps any more.
o
If you singleton is truly mutable, provide concurrency-safe update API, for example using AtomicReference, otherwise your code is buggy for concurrent cases even on JVM
d
But AtomicReference is the part of Kotlin Native. So as I understand the only way to implement such mutable singletons is declare them in common module as "expect" and then implement them for each platform independently? Correct?
o
Yes, but similar implementation on JVM makes sense as well, so maybe abstraction level around AtomicReference would be better
k
I did expect/actual wrapper for timber. Look for NativeBox here https://github.com/touchlab/timber/blob/native/common/src/main/kotlin/timber/log/Timber.kt
NativeBox basically does nothing on jvm