Daniele B
09/15/2020, 3:15 PMclass 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?aleksey.tomin
09/15/2020, 3:21 PMval lastUpdate: AtominRef<String?> = AtominRef(null)
val countriesListWithSummary: AtominRef<List<CountrySummary>> = AtominRef(emptyList())
…
countriesListWithSummary.value = someList.freeze()
louiscad
09/15/2020, 3:23 PM@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.Daniele B
09/15/2020, 3:24 PMlouiscad
09/15/2020, 3:25 PM@ThreadLocal
Daniele B
09/15/2020, 3:25 PMlouiscad
09/15/2020, 3:25 PMlouiscad
09/15/2020, 3:25 PMDaniele B
09/15/2020, 3:25 PMaleksey.tomin
09/15/2020, 3:26 PM@ThreadLocal
variable has different states for each thread - isn’t it?aleksey.tomin
09/15/2020, 3:27 PMDispatchers.Main
thread set some state but another thread will be read initial state 🙂louiscad
09/15/2020, 3:27 PMDaniele B
09/15/2020, 3:28 PM