Last active
March 17, 2019 15:27
-
-
Save fornewid/84a496c2b2e28c3c87d1e6397941246b to your computer and use it in GitHub Desktop.
Lazy ViewModel with Dagger2
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
// SpeakerFragment.kt | |
class SpeakerFragment : BaseFragment() { | |
private val speakerViewModel by viewModel<SpeakerViewModel>() | |
} | |
// BaseFragment.kt | |
abstract class BaseFragment : DaggerFragment() { | |
@Inject | |
lateinit var viewModelFactory: ViewModelProvider.Factory | |
protected inline fun <reified VM : ViewModel> viewModel(): Lazy<VM> = | |
lazy { viewModelProvider<VM>(viewModelFactory) } | |
protected inline fun <reified VM : ViewModel> activityViewModel(): Lazy<VM> = | |
lazy { activityViewModelProvider<VM>(viewModelFactory) } | |
protected inline fun <reified VM : ViewModel> parentViewModel(): Lazy<VM> = | |
lazy { parentViewModelProvider<VM>(viewModelFactory) } | |
} | |
// Extensions.kt | |
/** | |
* For Fragments, allows declarations like | |
* ``` | |
* val myViewModel = viewModelProvider(myViewModelFactory) | |
* ``` | |
*/ | |
inline fun <reified VM : ViewModel> Fragment.viewModelProvider( | |
provider: ViewModelProvider.Factory | |
) = ViewModelProviders.of(this, provider).get(VM::class.java) | |
/** | |
* Like [Fragment.viewModelProvider] for Fragments that want a [ViewModel] scoped to the Activity. | |
*/ | |
inline fun <reified VM : ViewModel> Fragment.activityViewModelProvider( | |
provider: ViewModelProvider.Factory | |
) = ViewModelProviders.of(requireActivity(), provider).get(VM::class.java) | |
/** | |
* Like [Fragment.viewModelProvider] for Fragments that want a [ViewModel] scoped to the parent Fragment. | |
*/ | |
inline fun <reified VM : ViewModel> Fragment.parentViewModelProvider( | |
provider: ViewModelProvider.Factory | |
) = ViewModelProviders.of(requireParentFragment(), provider).get(VM::class.java) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment