Skip to content

Instantly share code, notes, and snippets.

@joaortk
Created October 17, 2019 20:11
Show Gist options
  • Save joaortk/7d4f8442fb14507a2aedb0a62423c73f to your computer and use it in GitHub Desktop.
Save joaortk/7d4f8442fb14507a2aedb0a62423c73f to your computer and use it in GitHub Desktop.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import dagger.MapKey
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import kotlin.reflect.KClass
@Suppress("UNCHECKED_CAST")
@Singleton
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T =
viewModels[modelClass]?.get() as T
}
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment