koin-annotations icon indicating copy to clipboard operation
koin-annotations copied to clipboard

Support falling back to factory on platforms without AndroidX ViewModel

Open jadar opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe. I specify my ViewModel modules differently on iOS and Android. On Android, I want the viewModel<> specifier. However, on iOS (I am using SwiftUI) I want this to be a normal factory<> specifier.

Describe the solution you'd like I'd like to be able to make the @ViewModel annotation fall back to @Factory on platforms that doesn't support viewModel natively.

BaseViewModel.kt

expect abstract class BaseViewModel()

BaseViewModel.ios.kt

actual abstract class BaseViewModel()

BaseViewModel.ios.kt

import androidx.lifecycle.ViewModel
actual abstract class BaseViewModel actual constructor(): ViewModel()

MyViewModel.kt

@FactoryViewModel
class MyViewModel: BaseViewModel()
@Module
@ComponentScan
class MyModule

Describe alternatives you've considered I can do this with an expect/actual module with pure Koin.

ViewModelModule.ios.kt

actual object MyModule {
  val module = module {
    factory<MyViewModel> { MyViewModel() }
  }
}

ViewModelModule.android.kt

actual object MyModule {
  val module = module {
    viewModel<MyViewModel> { MyViewModel() }
  }
}

Target Koin project koin-annotations

jadar avatar Dec 04 '24 21:12 jadar

could be an option

arnaudgiuliani avatar Feb 20 '25 11:02 arnaudgiuliani

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 20 '25 12:07 stale[bot]