Hi Foks, I’m getting `kotlin.native.concurrent.Inv...
# multiplatform
s
Hi Foks, I’m getting
kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen
exception.
Copy code
Dependencies info -
kotlin = "1.4.30"
coroutines = "1.4.2-native-mt"
serialization = "1.0.1"
ktor = "1.4.2"
This is what I’m doing -
Copy code
class Manager {
 var user: User
 init(){
  GlobalScope.async(context = Dispatchers.Default) {
  val result = callToSuspendFunction
  user = result //ERROR ON THIS LINE
 }
}
How to achieve something like this?
u
You can not. You can't access a mutable variable (user) from two threads. Here
user
was probably created on the main thread and is written from default dispatcher.
s
Thanks for your quick response @uli. Yes, I’m calling this init from main thread.
v
i think you can assign value using
MainScope
or using the
Dispatchers.Main
k
You can use
AtomicReference
. In your case it would simply be:
Copy code
val user: AtomicReference<User?> = AtomicReference(null)
If you’re writing a multiplatform code you could be interested in on of those two libraries: https://github.com/Kotlin/kotlinx.atomicfu https://github.com/touchlab/Stately You can read more about why it’s needed here: https://kotlinlang.org/docs/mobile/concurrent-mutability.html