Created
February 4, 2018 22:11
-
-
Save mladenrakonjac/30f66e255c8456f08722d39f19c96459 to your computer and use it in GitHub Desktop.
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 DaggerAwareViewModelFactory @Inject constructor( | |
private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>> | |
) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
var creator: Provider<out ViewModel>? = creators[modelClass] | |
if (creator == null) { | |
for ((key, value) in creators) { | |
if (modelClass.isAssignableFrom(key)) { | |
creator = value | |
break | |
} | |
} | |
} | |
if (creator == null) { | |
throw IllegalArgumentException("unknown model class " + modelClass) | |
} | |
try { | |
@Suppress("UNCHECKED_CAST") | |
return creator.get() as T | |
} catch (e: Exception) { | |
throw RuntimeException(e) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment