What's the current approach for using ViewModels w...
# multiplatform
d
What's the current approach for using ViewModels when targeting Android, iOS and desktop (JVM target)? I've looked into some libs, especially moko-mvvm and KMM-ViewModel. My current plan is to split between Android/iOS with KMM-ViewModel and for desktop to do it separately (with custom code). Is there an easier approach to do it with one lib and reuse the code for all three targets?
r
Not really helpful, but would love to know more about this usecase. How would a JVM ViewModel look in terms of functionality?
c
The approach I’ve taken with the Ballast MVI library is to define all the logic in some “container” object that needs to live in a “host ViewModel”. The host VMs are the class that’s actually bound to the platform-specific lifecycles, but still allows you to keep all VM-related logic inside commonMain. This is a pattern that’s pretty common among similar libraries, rather than extending a base class that’s defined expect/actual declarations
d
@Rick Clephas I want to do an approach that sounds very similar to that of @Casey Brooks: • VM in combination with a "MVI-ish" style of state, events and reducer for UI updates • Using a flow (or just the state) in the UI to collect state changes, sending events back to the VM for the reducer/state transition • Handling lifecycle of the injected dependencies with the lifecycle of the VM My idea was that with a shared VM I have only to implement the logic of state transitions and events once. Not sure if that answers the question and if my ideas really applicable to the way VM could be used in the different platforms. Btw. I saw that there's an issue from @John O'Reilly in your lib about it. Not sure if he had a similar use case in mind.
r
Yeah that's a similar use case. It's probably not that difficult to support other targets (JVM or any other). It's just that I am unsure what the VM equivalent for such targets would be. In your case would it be sufficient if the VM is a simple/dumb abstract class? What / when should the onCleared function be called? Feel free to add more details and or use cases to that issue.
d
I think it would be sufficient to have an abstract class. So I might could abstract it myself for desktop and use KMM-ViewModel for iOS/Android. Not 100% sure if that works, therefore I will try it out and see where it gets me. For desktop "when to call onCleared" is really a good point. Foreground/background makes no sense, the point I can think of is when the "screen" (what ever that means) is left. I will try it out with an abstraction and might come back to the issue when I have more details and ideas. Thanks for the input and also bringing up these important questions.