https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
l

Lou Morda

09/25/2019, 7:21 PM
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

Kris Wong

09/25/2019, 7:28 PM
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

Lou Morda

09/25/2019, 7:31 PM
hmm, im gonna try that now, thanks!
e

Erik Christensen

09/25/2019, 10:09 PM
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

alex009

09/26/2019, 1:06 AM
Yes, we sharing and publish library with mvvm components https://github.com/icerockdev/moko-mvvm
👍 2
l

Lou Morda

10/02/2019, 8:43 PM
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

clhols

12/09/2019, 9:18 PM
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.
18 Views