Created
October 22, 2021 17:13
-
-
Save ferazog/25ca6257e5e9e63c2a12c1271f19a87f to your computer and use it in GitHub Desktop.
This file contains 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 @Inject constructor( | |
private val viewModelsMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> | |
) : ViewModelProvider.Factory { | |
override fun <T : ViewModel?> create(modelClass: Class<T>): T { | |
val creator = viewModelsMap[modelClass] ?: viewModelsMap.asIterable().firstOrNull { | |
modelClass.isAssignableFrom(it.key) | |
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass") | |
try { | |
@Suppress("UNCHECKED_CAST") | |
return creator.get() as T | |
} catch (e: Exception) { | |
throw RuntimeException() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment