Created
December 4, 2020 04:44
-
-
Save alaershov/969090d13d0bf33c356286e62a33d369 to your computer and use it in GitHub Desktop.
ViewModel + Dagger
This file contains hidden or 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
interface MyComponent { | |
val myViewModelFactory: ViewModelFactory<MyViewModel> | |
} |
This file contains hidden or 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
class MyFragment : Fragment() { | |
private val component: MyComponent // это твой даггер компонент | |
private val viewModel: MyViewModel by viewModels { // это стандартный делегат для вьюмоделей из AndroidX | |
component.myViewModelFactory | |
} | |
} |
This file contains hidden or 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
class MyViewModel | |
@Inject | |
constructor( | |
private val myInteractor: MyInteractor, | |
// остальные зависимости | |
) : ViewModel() { | |
// обычныф ViewModel | |
} |
This file contains hidden or 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
/** | |
* Creates an instance of a ViewModel of type VM | |
* by injecting it from DI graph via Provider<VM>. | |
*/ | |
class ViewModelFactory<VM : ViewModel> @Inject constructor( | |
private val viewModelProvider: Provider<VM> | |
) : ViewModelProvider.Factory { | |
@Suppress("UNCHECKED_CAST") | |
override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModelProvider.get() as T | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment