Last active
February 27, 2024 21:23
-
-
Save Sal7one/7e22535a1d6d266448a5f002aea85694 to your computer and use it in GitHub Desktop.
Assisted Injection with hilt Helper code - I think it's dumb and a bad practice but here's the code anyways :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Raw hilt viewmodel | |
@HiltViewModel | |
class SomeViewModel @Inject constructor( | |
private val repository: Repo // Injected from hilt | |
) : ViewModel() { | |
} | |
// Let's pass any var we want for example an int that we pass when we create the viewmodel | |
// NOTICE: REMOVE @HiltViewModel | |
class SomeViewModel @AssistedInject constructor( | |
private val repository: Repo, | |
@Assisted // NOTICE | |
private val anINtttttt: Int, | |
) : ViewModel() { | |
@AssistedFactory | |
interface Factory { | |
fun create(anINtttttt: Int) : SomeViewModel | |
} | |
companion object { | |
fun provideSomeViewModelFactory(factory: Factory, anINtttttt: Int) : ViewModelProvider.Factory { | |
return object: ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
return factory.create(anINtttttt) as T | |
} | |
} | |
} | |
} | |
} | |
// Usage In Activity/Fragment (Compose version below) | |
@Inject lateinit var factory: SomeViewModel.Factory | |
val mySuperSpecialInt = 12634209 | |
private val viewModel: SomeViewModel by viewModels { | |
SomeViewModel.provideSomeViewModelFactory(factory, mySuperSpecialInt) | |
} | |
// now in onCreate() | |
// viewModel.DoThing() | |
// Compose | |
// Extra Di file | |
@EntryPoint | |
@InstallIn(ActivityComponent::class) | |
interface ViewModelFactoryProvider { | |
fun someViewModelFactory(): SomeViewModel.Factory | |
} | |
// Inisde composable route | |
val factory = EntryPointAccessors.fromActivity( | |
LocalContext.current as Activity, | |
ViewModelFactoryProvider::class.java | |
).someViewModelFactory() | |
val mySuperSpecialInt = 12634209 | |
val viewModel: SomeViewModel = viewModel(factory = SomeViewModel.provideSomeViewModelFactory(factory, mySuperSpecialInt)) | |
// now | |
// viewModel.DoThing() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment