Last active
December 5, 2019 15:05
-
-
Save chibatching/489599b12dbbf4aa434113a363316ea1 to your computer and use it in GitHub Desktop.
Simple ViewModel Dagger Injection
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
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 } | |
) | |
} |
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
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