Anybody sharing ViewModel code between iOS and And...
# multiplatform
l
Anybody sharing ViewModel code between iOS and Android? I'd like to have the ViewModels be shared code, but it looks like the downside is that a custom ViewModel in the shared code would not be tied to the Android lifecycle like in the jetpack libraries. Has anyone come across this design decision and could offer advice? Thanks!
k
seems like you could declare an expect class to use as the super type, which you could typealias to ViewModel for Android targets
👍 1
l
hmm, im gonna try that now, thanks!
e
Alternatively, you could have Android view models with a reference to a common "view model" or whatever you want to call it -- basically, a lifecycle-aware wrapper.
👍 1
a
Yes, we sharing and publish library with mvvm components https://github.com/icerockdev/moko-mvvm
👍 2
l
I was also thinking of using an interface that would have functions that are implemented by default.
UsersViewModel: ViewModel(), SharedViewModel
where the ViewModel is the android jetpack viewmodel and has very little logic but keeps all of the state, and the SharedViewModel would be an interface that would contain all of the logic and have zero state.
c
Or use the interface to do class delegation to the implementation class where all the logic and state is:
class UsersViewModel: ViewModel(), SharedViewModel by SharedViewModelImpl()
It just complains about the override of onCleared(), so you can add
DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE
to ignore that.