Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple ViewModel Dagger Injection
import androidx.fragment.app.viewModels
import dagger.android.support.DaggerFragment
class SomeFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelFactory<SomeViewModel>
private val viewModel: SomeViewModel by viewModels { viewModelFactory }
@Inject
lateinit var parentViewModelFactory: ViewModelFactory<ParentViewModel>
private val parentViewModel: ParentViewModel by viewModels(
{ requireActivity() },
{ parentViewModelFactory }
)
}
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
class ViewModelFactory<T : ViewModel>
@Inject constructor(
private val provider: Provider<T>
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return provider.get() as T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment