Hi, I have a more MVI-related question. In my app ...
# orbit-mvi
r
Hi, I have a more MVI-related question. In my app I have a number of logically related screens such as a questionnaire where multiple screens are displayed with questions and then finally a result screen is shown. These screens share a view model (which seems the correct thing to do). The issue arises where state needs to be kept across screens (but not necessarily displayed). So for example, a flow of screens is started with some important information at the beginning (say the questionnaire was started in beginner or advanced mode and this is needed at the last step to talk to some api. I could store the information as an instance field in the view model but you have to be careful about making sure fields are set before using and then reset as view models can outlive the screens. I was wondering could I put this state into the view state class? Or is this not a good idea?
m
Can the state of individual screens be represented as sealed class subclasses? Then you can store shared state in the base.
I mean that’s how I’d do it but it depends on whether this fits your particular architecture
b
As a general rule, I avoid sharing VMs unless I have no other choice. I've realised that usually people tend to use a "ParentViewModel" just to keep track of some state, where this state could be passed around. Instead, I prefer passing the state to my Fragments/Composables Each piece of UI passing data to the next. Also like Mikolaj said, you want to use sealed classes and model your state in such a way that makes it impossible to create these Fragments/Composables without the appropriate state
r
it sounds like you are advocating instance variables in the VM
having separate VMs per screen and passing the data along will work but its more work for little benfit
b
It is more work indeed, but you get a bunch of benefits: • Your screen are independent from one another and thus easier to re-use • Your compiler prevents you from reaching undesired state Then it's up to you to decide wether this is worth doing the extra work, or if you'd rather throw runtime Exception if you reach an undesired state and just use unit tests, rather than the compiler, to assert the correctness of your code
☝️ 1
r
If its ok to carry non-ui state across intents and view state objects, I think it matters less if i have one VM or many
b
In my opinion it's ok to carry non-UI state using Intents. I tend to do it quiet a lot to ensure that a screen always has what it needs to work, rather than relying on some parent VM to hold the data
🙌 1