Osman Saral06/03/2021, 7:20 AM
Nicklas Jensen06/03/2021, 7:40 AM
Given 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.
Osman Saral06/03/2021, 8:23 AM
branch of coroutines prevent the exception? or should I use
to be sure about the freeze state?
Nicklas Jensen06/03/2021, 8:44 AM
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
(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
(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 Gunnarss06/03/2021, 9:40 AM
Osman Saral06/03/2021, 12:57 PM
kpgalligan06/03/2021, 1:35 PM
, 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
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.