Skip to content

Instantly share code, notes, and snippets.

Lewis Evans lewisevans

  • Lewis Evans Limited
  • London
Block or report user

Report or block lewisevans

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View MyFragment.kt
class MyFragment : BaseFragment<MyViewModel>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = viewModelWith(activity!!)
with(viewModel) {
/*DO SOME STUFF HERE*/
}
}
}
View BaseFragment.kt
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)
View BaseActivity.kt
abstract class BaseActivity<VM : BaseViewModel> : DaggerAppCompatActivity() {
@Inject
internal lateinit var viewModelFactory: ViewModelFactory<VM>
protected lateinit var viewModel:VM
internal inline fun <reified VM : ViewModel> viewModelWith(act: FragmentActivity): VM =
ViewModelProviders.of(act, viewModelFactory).get(VM::class.java)
}
View ViewModelFactory.kt
class ViewModelFactory <T : ViewModel> @Inject constructor(private val viewModel: Lazy<T>) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModel.get() as T
}
You can’t perform that action at this time.