Last active
March 9, 2018 05:10
-
-
Save seisuke/1bf03023767edc384477742cf889f6b2 to your computer and use it in GitHub Desktop.
Kotlin way ViewModelFactory with 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
import android.arch.lifecycle.ViewModel | |
import android.arch.lifecycle.ViewModelProvider | |
import javax.inject.Inject | |
import javax.inject.Provider | |
import javax.inject.Singleton | |
@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 { | |
val creator = creators[modelClass] | |
?: creators.entries.firstOrNull { (key, _) -> | |
modelClass.isAssignableFrom(key) | |
}?.value | |
?: throw IllegalArgumentException("unknown model class " + modelClass) | |
return creator.get() as T | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment