Last active
August 24, 2022 10:52
-
-
Save bhavesh3005sharma/6e5068c913703fb745316399ba0734ae to your computer and use it in GitHub Desktop.
Script demonstrating the use of @AssistedInject & @AssistedFactory in case parameterized viewmodel
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
@AndroidEntryPoint | |
class SampleActivity : AppCompatActivity() { | |
@Inject lateinit var factory: SampleViewModelFactory | |
val viewModel: SampleViewModel by viewModels { | |
SampleViewModel.provideFactory( | |
factory, | |
"data" | |
) | |
} | |
} |
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
class SampleRepository @Inject constructor { | |
........ | |
........ | |
} |
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
@HiltViewModel | |
class SampleViewModel @AssistedInject constructor( | |
@Assisted("key") key : String?, | |
var sampleRepository: SampleRepository | |
) : ViewModel() { | |
........ | |
........ | |
companion object { | |
fun provideFactory( | |
assistedFactory: SampleViewModelFactory, | |
key: String? | |
): ViewModelProvider.Factory = object : ViewModelProvider.Factory { | |
@Suppress("UNCHECKED_CAST") | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
return assistedFactory.create(key) as T | |
} | |
} | |
} | |
} |
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
@AssistedFactory | |
interface SampleViewModelFactory { | |
fun create( | |
@Assisted("key") key: String? | |
) : SampleViewModel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment