Osman Saral
06/03/2021, 7:20 AMNicklas Jensen
06/03/2021, 7:40 AMGiven multiple threads, when an object (instance of a class) is referenced from code executing on another thread from what it was created on, that object will automatically become frozen. A frozen object is immutable and thus can no longer be mutated (e.g. callingAs to whether you need to dive into them and learn as a KMM beginner - it depends on the type of application you’re looking to build while learning 🙂on a.add()
, or setting a property on the object) for the lifetime of the process/application, nor can any objects referenced by the frozen object, as those too will become frozen. Attempting to mutate a frozen object will throw an exception.MutableList<T>
Osman Saral
06/03/2021, 8:23 AMnative-mt
branch of coroutines prevent the exception? or should I use ensureNeverFrozen
to be sure about the freeze state?Nicklas Jensen
06/03/2021, 8:44 AMnative-mt
branch does not prevent freezing of objects by itself, nor does it prevent the exception when attempting to mutate a frozen object. You don’t need ensureNeverFrozen()
(my team doesn’t use it at all). If your object is frozen (as the result of it being referenced by code executing on another thread), an exception will be thrown as soon as any part of your code attempts to mutate it, though any and all threads are allowed to read it at any given time. If you do need mutable shared state you can use an AtomicReference
(e.g. from Stately), but you could also use some kind of event/message queue (e.g. the Main dispatcher) for all reads and writes of the state, effectively limiting all access to the state to a single thread.Siggi Gunnarss
06/03/2021, 9:40 AMOsman Saral
06/03/2021, 12:57 PMkpgalligan
06/03/2021, 1:35 PMensureNeverFrozen
, you definitely need to understand it, or you'll have a crap time debugging issues later. We use it for "View Model" level state in common code, as we're very intentional about what is and is not frozen.
If your object is frozen (as the result of it being referenced by code executing on another thread), an exception will be thrown as soon as any part of your code attempts to mutate it,True. What you don't know (in complex cases) is how it was frozen, and when, which you need to know to debug the problem. That's what
ensureNeverFrozen
is for. You can just add that when debugging, but we use it on certain classes all the time, to ensure it's doing what we expect as development continues, especially with larger teams, or as devs new to KMP are contributing to the project. I will mistakenly freeze objects sometimes too, though. It's it easy to do by mistake.