https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
s

sushma nayak

05/05/2021, 8:22 PM
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

uli

05/05/2021, 8:27 PM
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

sushma nayak

05/05/2021, 8:47 PM
Thanks for your quick response @uli. Yes, I’m calling this init from main thread.
v

Vitor Prado

05/05/2021, 8:58 PM
i think you can assign value using
MainScope
or using the
Dispatchers.Main
k

KamilH

05/06/2021, 5:44 AM
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
3 Views