Created
April 5, 2024 10:39
-
-
Save nizarfadlan/d13749473ceccde17f7c2484106e2b1c to your computer and use it in GitHub Desktop.
ViewModelFactory
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 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