Created
July 10, 2019 10:04
-
-
Save egek92/ce5f1b2bae85f0f18b202773c65003d3 to your computer and use it in GitHub Desktop.
ViewModelInjectionDagger.kt
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
@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 | |
internal annotation class ViewModelKey(val value: KClass<out ViewModel>) | |
@Module | |
abstract class ViewModelModule { | |
@Binds | |
internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory | |
@Binds | |
@IntoMap | |
@ViewModelKey(PostListViewModel::class) | |
internal abstract fun postListViewModel(viewModel: PostListViewModel): ViewModel | |
//Add more ViewModels here | |
} | |
//and inside your Activity | |
@Inject | |
lateinit var viewModelFactory: ViewModelProvider.Factory |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment