Created
July 29, 2019 18:29
-
-
Save AfzalivE/7c363a955358d957d825f59b7d5618ee to your computer and use it in GitHub Desktop.
ViewModelFactory for Dagger2
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
/** | |
* Constructs a ViewModelFactory with dependencies | |
*/ | |
@Singleton | |
class ViewModelFactory @Inject constructor( | |
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> | |
) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
var creator = creators[modelClass] | |
if (creator == null) { | |
creator = creators.entries.firstOrNull { | |
return@firstOrNull modelClass.isAssignableFrom(it.key) | |
}?.value | |
if (creator == null) { | |
throw IllegalArgumentException("Unknown model class $modelClass, have you declared this class in ViewModelModule?") | |
} | |
} | |
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