Hi all, I’m working on moving business logic from ...
# multiplatform
a
Hi all, I’m working on moving business logic from my Android module into a shared multiplatform module to use on the iOS side as well. I’ve cloned the KaMP repo to see how they implemented ViewModel behavior across platforms, and saw they have an expect/actual situation:
expect abstract class ViewModel()
with one open function
onCleared()
. The ViewModel instances are accessed through Koin with this function:
fun getBreedViewModel() = getKoin().get<BreedViewModel>()
, which is called from SwiftUI like so:
let viewModel = KotlinDependencies.shared.getBreedViewModel()
. I’ve also cloned the FantasyPremierLeague app, which uses the actual
androidx.lifecycle.ViewModel
as a base class for its ViewModel classes in the shared module, and then creates instances of ViewModels in Swift code with an Owner class:
class SharedViewModelStoreOwner<VM : ViewModel> : ObservableObject, ViewModelStoreOwner
. As a caveat just to make things more complicated, I was planning on using Storyboards in my iOS app, since I haven’t worked with SwiftUI yet (primarily an Android dev). Any advice on which approach to take here? I’ve tried to emulate the Fantasy Premier League app, since using the actual androidx ViewModel class is ideal, but haven’t gotten it to work. Asking for a friend 🙏
f
I have a UIKit example
You can choose the way you want, the only thing which need to be respected, is the lifecycle of the KMP ViewModel
a
Awesome, thank you! I’ll check those out this week, appreciate it lots
j
@Alex Mortimer I highly recommend just start using SwiftUI over UIKIt, much less code to write and much simpler to get a UI up and running. Then once you start using Compose UI on Android, the UI Code on both platforms will look structurally identical.
a
@Jason fair enough, I should make the jump. Do you recommend doing each platform’s UI separately still, in Compose and SwiftUI, or use Compose Multiplatform for the whole project?
j
I recommend not using CMP until it is much more mature, maybe for just small / easy secondary screens it would work fine. I code in both SwiftUI/ComposeUI and don't have any issues building complex UI's. They are so much more simpler to build once you get the hang of it
a
Got it, thanks! That’s what I figured
j
@Alex Mortimer also that's the only platform specific code I write, the rest is all in KMP, except for a few platform specific services or wrappers, but 98% of the code on iOS/Android is just the declarative view layer. ViewModels are in KMP, same w/ Services, Domain Objects, etc.