Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Created May 12, 2020 18:20
Show Gist options
  • Save marcellogalhardo/09c4417860cf65352099c0148f27eddc to your computer and use it in GitHub Desktop.
Save marcellogalhardo/09c4417860cf65352099c0148f27eddc to your computer and use it in GitHub Desktop.
package com.marcellogalhardo.viewmodel.factory
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
/**
* A [ViewModelProvider.Factory] that can hold a ViewModel [producer] function
* to be used with [ViewModelProvider] and [viewModels].
*
* When using the [Inject] constructor with Dagger, it will automatically
* get a [Provider] for the [VM] available in your current scope.
*/
class ViewModelFactory<VM : ViewModel> constructor(
private val producer: () -> VM
) : ViewModelProvider.Factory {
/**
* An internal constructor to be used when injecting with Dagger.
*/
@Inject
internal constructor(provider: Provider<VM>) : this(provider::get)
@Suppress("UNCHECKED_CAST")
override fun <VM : ViewModel?> create(modelClass: Class<VM>): VM {
return producer() as? VM
?: error("${modelClass.name} cannot be provided without an @Inject constructor or from a @Provides-annotated method.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment