Skip to content

Instantly share code, notes, and snippets.

@arekolek
Last active May 16, 2018 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arekolek/e5083776d263b16666aff38dd0d3c439 to your computer and use it in GitHub Desktop.
Save arekolek/e5083776d263b16666aff38dd0d3c439 to your computer and use it in GitHub Desktop.
package com.example
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
/**
* Lets us use [Inject] annotations on [ViewModel] classes.
*
* To use it, include the [ViewModelModule] in the module that binds the ViewModel itself.
*/
class ViewModelFactory @Inject constructor(
private val providers: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
// check if modelClass is provided or is a superclass of provided one
val provider = providers[modelClass]
?: providers.entries.find { modelClass.isAssignableFrom(it.key) }?.value
?: throw IllegalArgumentException("Unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return provider.get() as T
} catch (e: Exception) {
throw RuntimeException("There was an error providing an instance of $modelClass", e)
}
}
}
package com.example
import android.arch.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@MapKey
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
annotation class ViewModelKey(val value: KClass<out ViewModel>)
package com.example
import android.arch.lifecycle.ViewModelProvider
import dagger.Binds
import dagger.Module
@Module
interface ViewModelModule {
@Binds
fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment