There's probably a better place to ask this, but h...
# multiplatform
d
There's probably a better place to ask this, but has anyone seen an example of sharing the new KMP-enabled Jetpack
lifecycle-viewmodel
between Android and iOS WITHOUT Compose Multiplatform involved?
f
👍🏻 1
m
cc: @Chris Cartland
c
The Android team also has an implementation with ViewModel using KMP without Compose Multiplatform. Check the Fruitties sample app. We have been iterating on a few improvements but you can see what we've done so far. https://github.com/android/kotlin-multiplatform-samples
f
I still don’t understand why do we need a StoreOwner with SwiftUI, that’s doesn’t fit well with the lifecycle of a SwiftUI Application
all that because the
onCleared
of the KMP ViewModel is private
after all, if it better with this kind of pattern, That’s ok 😄
c
If you rewind the Android git history by a month, then the Fruitties app doesn't really implement a ViewModelStoreOwner. It just uses ViewModel on iOS in a very basic way. The ViewModel is basically instantiated at app startup and lives for the life of the app. If you are ok with that, then there isn't really a need for the lifecycle features of the ViewModelStoreOwner. The goal of a ViewModelStoreOwner is to scope a set of ViewModel instances to part of the app. If you never go to that part of the app, the ViewModel is/are never instantiated. If you leave that part of the app, the ViewModel is/are cleaned up. We implemented the lifecycle on iOS using SwiftUI NavigationStack. We provide a ViewModelStoreOwner inside a NavigationLink. Each NavigationLink will go in and out of scope based on the user navigation, so the ViewModelStore is created when the user navigates to that part of the app, and it is cleared when the user navigates away. If you want your ViewModel instantiation to be scoped to the SwiftUI lifecycle, this example is one way to do it with ViewModel. https://github.com/android/kotlin-multiplatform-samples/blob/main/Fruitties/iosApp/iosApp/ui/ContentView.swift
Copy code
NavigationLink {
    ViewModelStoreOwnerProvider {
Copy code
FruittieScreen(fruittie: value)
    }
} label: {
    FruittieView(fruittie: value)
}
f
@Chris Cartland One last thing: after I played with the app 🙂 . The
ViewModelStore
solves a SwiftUI lifecycle issue by bringing in a Kotlin Compose concept. Yeah, it works, it’s just too exotic for me to keep a ViewModel alive in contrast to a classic SwiftUI ViewModel. Just I don’t like the use of
onDisappear
event to control the deletion of the view model unlike the SwiftUI ViewModel which is based on the deinit.