Hi! Now that the Jetpack lifecycle and view model libraries have multiplatform support, I was wondering if this library could be made multiplatform compatible. In my case, I'm thinking of iOS, and being able to scope a ViewModel to a SwiftUI View.
I know of two solutions so far:
-
KMP-ObservableViewModel solution where using the @StateViewModel annotation will take care of the lifecycle and ensure the view model is cleared when the View is destroyed
-
This solution, that I'm currently using myself, and seems to work fine, though there's a bit of boilerplate involved (maybe because I don't know any better):
In the iOS app, create a ViewModelOwner class that implements the ViewModelOwner interface. This requires the shared module to export the Jetpack viewmodel library.
// ViewModelStoreOwner.swift
import shared
class ViewModelStoreOwner: shared.ViewModelStoreOwner {
internal let viewModelStore = ViewModelStore()
fileprivate func put<VM: ViewModel>(_ vm: VM) {
viewModelStore.put(key: VM.self.description(), viewModel: vm)
}
// This is called when the View containing this object is destroyed
deinit {
viewModelStore.clear()
}
}
// A helper function to create a ViewModel with an owner
func viewModel<VM: ViewModel>(owner: ViewModelStoreOwner, _ factory: () -> VM) -> VM {
let vm = factory()
owner.put(vm)
return vm
}
Then in a View implementation:
// SomeView.swift
import SwiftUI
struct SomeView: View {
private let owner = ViewModelStoreOwner()
private let vm: SomeViewModel
init() {
vm = viewModel(owner: owner) {
SomeViewModel()
}
}
var body: some View {
// etc
}
}
I'm using the second method because I don't need all the other stuff KMP-ObservableViewModel offers - I prefer to use SKIE to handle Flows.
But I started wondering if it wouldn't be possible to make viewModelScoped() work inside a SwiftUI View.
Best regards,
/Emil
Hi! Now that the Jetpack lifecycle and view model libraries have multiplatform support, I was wondering if this library could be made multiplatform compatible. In my case, I'm thinking of iOS, and being able to scope a
ViewModelto a SwiftUIView.I know of two solutions so far:
KMP-ObservableViewModel solution where using the
@StateViewModelannotation will take care of the lifecycle and ensure the view model is cleared when theViewis destroyedThis solution, that I'm currently using myself, and seems to work fine, though there's a bit of boilerplate involved (maybe because I don't know any better):
In the iOS app, create a
ViewModelOwnerclass that implements theViewModelOwnerinterface. This requires the shared module to export the Jetpack viewmodel library.Then in a
Viewimplementation:I'm using the second method because I don't need all the other stuff
KMP-ObservableViewModeloffers - I prefer to use SKIE to handleFlows.But I started wondering if it wouldn't be possible to make
viewModelScoped()work inside a SwiftUIView.Best regards,
/Emil