working with large existing native codebases (Swif...
# multiplatform
w
working with large existing native codebases (SwiftUI, Jetpack Compose for all new stuff), I want to refactor native ViewModels into KMP code. Should I use KMP’s ViewModel or start with a library like moko’s MVVM?
the docs for KMP ViewModel seems targeted at Compose Multiplatform
and moko MVVM predates the KMP ViewModel, right?
p
Just an opinion, keep the ViewModel in swift and share kmp from the domain layer down, UseCases in CLEAN terminology. Cabling these ViewModels(any library) to swiftui requires a lot of work. Easier to share a UseCase that has a plain(not suspend or FlowT) function that returns a sealed ResultT
j
I would use androidx Viewmodel. Get a feeling Jetbrains and Google streamline a lot and going into a clean direction. Also its easier for compose code align into. But depends ofc how swift ui code looks like.
f
@Wes Cook using the KMP viewmodel is possible with iOS, but with some helper to write. Look at my exploration.
w
thank you for your responses. I appreciate you sharing your repo @François. Looks like a good place to start.
f
Yes, It’s a starting point, I don’t want to impose something, The management of the KMP VM’s lifecycle on iOS is totally new.
p
I find two tricky things when sharing at the ViewModel level: 1- ViewModel lifecycle management from iOS. 2- Transforming events from STateFlowT to swiftui @Observable State.
w
noob question: if you wrap your KMP ViewModel as a ObservableObject, what part of the lifecycle concerns does that leave to me?
Copy code
class SharedViewModel<VM: ViewModel>: ObservableObject {
f
By wrapping, the lifecycle of KMP VM is sync with the ObservableObject lifecycle (which is also used for SwiftUI VM).
Also, you need to manage some case like this one.
like SwiftUI async method but kind of differently.
p
But will that automatically call ViewModel::onCleared() once the swiftui component/screen is detached/unmounted?
f
Yes, that’s the goal.
💯 1
🙏 1