Skip to content

Instantly share code, notes, and snippets.

@lewisevans
Created November 15, 2018 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lewisevans/74f8d2631157e088db9a0e2dce358973 to your computer and use it in GitHub Desktop.
Save lewisevans/74f8d2631157e088db9a0e2dce358973 to your computer and use it in GitHub Desktop.
abstract class BaseFragment<VM : BaseViewModel> : DaggerFragment() {
@Inject
internal lateinit var viewModelFactory: ViewModelFactory<VM>
protected lateinit var viewModel: VM
internal inline fun <reified VM : ViewModel> viewModelWith(frag: Fragment): VM =
ViewModelProviders.of(frag, viewModelFactory).get(VM::class.java)
internal inline fun <reified VM : ViewModel> viewModelWith(act: FragmentActivity): VM =
ViewModelProviders.of(act, viewModelFactory).get(VM::class.java)
}
@lewisevans
Copy link
Author

Use it in Fragment like: viewModel = viewModelWith(activity!!) and it's automatically cast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment