Hi! How can we share ViewModel across platforms in...
# multiplatform
a
Hi! How can we share ViewModel across platforms in compose Multiplatform?
p
Compose-multiplatform is one single code base, place all compose/viewmodel stuff in commonMain.
a
@Pablichjenkov As you know, ViewModel is a special class that survives across configuration changes. So one solution is expect/actual. Is there any other solution?
@amezcua Other than expect/actual approach?
a
Looking in the history I've found this
BTW: I'm not
@amezcua
😅
a
I just saw the first name..😅
p
That VM behavior is only on Android. There are a couple of libraries that mimic the behavior to other platforms but in my opinion is a waste of energy because those platforms never had interest in process death recover or they don't suffer from things like Activity death on device rotation
If you ask me I would say Android is the wrong platform here
A lot of ceremony for a problem that can/should be avoided by simply handling configuration changes at the code level, not killing the Activity.
Anyways, Decompose I believe ported this behavior to the other lands. Voyager did it too but I believe they don't support iOS, haven't checked their repo in a while. There might be some other project on GitHub doing that, do a lookup there
a
If you want to have the android viewmodel in common code, just expect-actual a class, that androidMain actuals it, extend it by ViewModel from androidx. Then you can make your other viewmodels in common extend the expected viewmodel. I dunno if you understand.
p
But he still needs to install it's VMs in a lifecycleowner. Meaning you will have to use Navigation Component or Fragments/Activity in Android. Then the code will get a bit fragmented between platforms. I think that approach fits better a KMM app but if you plan to go compose-multiplatform better use the libraries I mentioned above or not using Android Viewmodel concept at all, just use compose State.
a
Oh compose-multiplatform! Didn't spot that. @Pablichjenkov you're right.
1755 Views