Joaquim Ley
09/29/2020, 1:51 PMby viewModel()
or wtv it suits you, you could even inject()
but on Swift seems like we don't have access to Koin's sugar.
--
Summarising:
View wants to create a ViewModel <- UseCase <- Repository <- RemoteApi
Note: '<-' Depends onJoaquim Ley
09/29/2020, 2:05 PMstreetsofboston
09/29/2020, 2:07 PMviewModel()
function.
We have an expect ViewModel
in the commonMain and the androidMain’s actual
of this extends the the jetpack ViewModel, the iosMain just makes a simple actual
out of it.
Then we have in the commonMain a bunch of ViewModelFactories that act as an assisted-inject. E.g. MyScreenViewModel
has a MyScreenViewModelFactory
and this factory is configured through Koin (in commonMain) with the necessary dependencies. These dependencies are then used to create a MyScreenViewModel
(this is much like the Assisted-Inject of Dagger).
In Android app:
class MyActivity : BaseActivityAndKoinComponent() {
val factory: MyScreenViewModelFactory = inject()
val viewModel by lazy { factory.create() }
...
}
In iOS:
...
let factory = MyScreenViewModelFactory.get()
....
let viewModel = factory.create()
To make this happen, iOS has the following extensions:
protocol KoinInjectable: AnyObject {
static func get(parameter: Any, qualifier: Koin_coreQualifier?) -> Self
}
extension KoinInjectable {
/// Creates and returns an instance of `Self`
///
/// If `Self` has not been registered with Koin, this will fail with an uncaught Kotlin exception.
static func get(parameter: Any = "", qualifier: Koin_coreQualifier? = nil) -> Self {
KoinIOS().get(objCClass: Self.self, qualifier: qualifier, parameter: parameter) as! Self
}
}
...
extension MyScreenViewModelFactory: KoinInjectable {}
and iosMain has the kotlin function get
defined for object KoinOS
.zalewski.se
09/29/2020, 3:31 PMJoaquim Ley
09/29/2020, 5:13 PM