Asking for opinions: is it preferable to have a sh...
# multiplatform
d
Asking for opinions: is it preferable to have a shared ViewModel or should the ViewModel be platform-specific? My app is currently targeting iOS and Android and using a shared ViewModel based on code from the Kotlin Multiplatform tutorial book from Kodeco.
a
I am sharing viewmodels with kmp native coroutines and kmp observable viewmodel and using a mix of swift ui and compose screens, worked out great so far
d
I think I may be doing something wrong then. How do you share changes to the viewmodel with your top level composables on both platforms? I'm, as I mentioned, using code I borrowed from Kodeco's KMP book and it acts like the state is causing the view model to change which causes the state to change, ad infinitum. If you look at this class: https://github.com/mcpierce/variant/blob/feature/issue-8/shared/src/commonMain/kotlin/org/comixedproject/variant/shared/model/VariantViewModel.kt I used their example to publish changes to the list of links to display: var onDisplayLinksUpdated: ((List<AcquisitionLink>) -> Unit)? = null set(value) { field = value onDisplayLinksUpdated?.invoke(acquisitionLinks) } This class is the root composable on the Android platform, and it subscribes to those changes to update the state variable that is the list of links to display: https://github.com/mcpierce/variant/blob/feature/issue-8/androidVariant/src/main/java/org/comixedproject/variant/android/ui/RootView.kt var displayLinks by remember { mutableStateOf(listOf<AcquisitionLink>()) } viewModel.onDisplayLinksUpdated = { displayLinks = it } I keep seeing the displays repeatedly updating, even though the display doesn't change itself at all and is responsive to clicks. Is this the wrong approach?
a
I don't understand exactly what top Composables means exactly 🤔
d
The root compostable function called from MainActivity.
a
are you going full compose multiplatform or using swift ui?
d
SwiftUI but I’ve only done a bit of it so far.
a
Well it really depends on the usecase, but In this case you can probably share the viewmodel and listen to the state and react to it the same way on both platforms
As i said I am using native coroutines and observable viewmodel and the logic is pretty much the same on both platforms whilst the ui staying mostly native
d
Can you point me to a good example or tutorial? I’m doing that now but as I mentioned it seems to be looping between view model events causing an update that causes the view model to update, etc.
a
You most likely need to explore your options and try some different approaches and see what works best for you
d
Thank you! I’ll take a look.
a
the android part/jvm is pretty much what you are used to already
this lib just makes it alot easier to feed the viewmodel to swiftui the same way you feed it to compose using state flows
👍 1