I have this Repository class in the `commonMain`: ...
# kotlin-native
d
I have this Repository class in the `commonMain`:
Copy code
class Repository {
    companion object Data {
        var lastUpdate: String? = null
        var countriesListWithSummary: List<CountrySummary> = emptyList()
    }
}
when I compile it for iOS, I get these warnings:
Variable in singleton without @ThreadLocal can't be changed after initialization
and on runtime I actually get this crash:
kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen mypackage.Repository.Data@3310e88
How should I handle this situation?
a
Copy code
val lastUpdate: AtominRef<String?> = AtominRef(null)
        val countriesListWithSummary: AtominRef<List<CountrySummary>> = AtominRef(emptyList())
Copy code
countriesListWithSummary.value = someList.freeze()
l
@Daniele B You need to decide whether you want it to be thread local, and in this case annotate it with
@ThreadLocal
, and only mutate it from the same thread (e.g. the main thread), or you need to have it immutable (the default, that can be made explicit with
@SharedImmutable
, at which point it wouldn't make sense to have a
var
, or, if you really need to have it mutable from multiple threads, you can use an atomic reference as Alexey Tomin is suggesting with his snippet.
d
I am actually going to modify them only from Dispatchers.Main
l
Then use
@ThreadLocal
d
so can @ThreadLocal be ok for that?
l
As the compiler is suggesting
yes, it will be local to the main thread
d
what about if there are concurrent coroutines on Dispatchers.Main ?
a
@ThreadLocal
variable has different states for each thread - isn’t it?
👌 2
Dispatchers.Main
thread set some state but another thread will be read initial state 🙂
l
@Daniele B It's no problem, just don't do the following: Reading the value, run suspending code and updating the value base on what you've read.
d
@louiscad it seems ok then! many thanks
👌 1