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)