Skip to content

Instantly share code, notes, and snippets.

@nizarfadlan
Created April 5, 2024 10:39
Show Gist options
  • Save nizarfadlan/d13749473ceccde17f7c2484106e2b1c to your computer and use it in GitHub Desktop.
Save nizarfadlan/d13749473ceccde17f7c2484106e2b1c to your computer and use it in GitHub Desktop.
ViewModelFactory
class ViewModelFactory private constructor(
private val githubRepository: GithubRepository
) :
ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DetailViewModel::class.java)) {
return DetailViewModel(githubRepository) as T
}
throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name)
}
companion object {
@Volatile
private var instance: ViewModelFactory? = null
fun getInstance(context: Context): ViewModelFactory =
instance ?: synchronized(this) {
instance ?: ViewModelFactory(
Injection.provideRepository(context)
)
}.also { instance = it }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment